Last Updated: February 25, 2016
·
1.951K
· rshetty

Rails #rewhere ActiveRecord method

Rails has introduced a "rewhere" method which according to official documentation

Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.

Consider you have a query as:

Post.where(published: true)    # => WHERE `published` = 1 

This code returns all the posts which have their published field set to true.

Consider this:

Post.where(published: true).where(published: false)   # => WHERE `published` = 1 AND `published` = 0

This code returns all the posts which have their published field set to true and also the ones set with false.

Rewhere method:

Post.where(published: true).rewhere(published: false)   # => WHERE `published` = 0

This code returns all the posts which have their published field set to false.

"Rewhere" method overrides the named where condition.

This is equivalent to unscope(where: conditions.keys).where(conditions).

Happy Hacking ...