Rails 5: ActiveRecord OR query Rails 5: ActiveRecord OR query ruby ruby

Rails 5: ActiveRecord OR query


The ability to chain or clause along with where clause in ActiveRecord query will be available in Rails 5. See the related discussion and the pull request.

So, you will be able to do the following things in Rails 5:

To get a post with id 1 or 2:

Post.where('id = 1').or(Post.where('id = 2'))

Some other examples:

(A && B) || C:

    Post.where(a).where(b).or(Post.where(c))

(A || B) && C:

    Post.where(a).or(Post.where(b)).where(c)


We don't need to wait for rails 5 to use this OR query. We can also used it with rails 4.2.3. There is a backport here.

Thank to Eric-Guo for gem where-or, Now we can add this OR functionality in >= rails 4.2.3 also using this gem.


(Just an addition to the answer by K M Rakibul Islam.)

Using scopes, the code can become prettier (depending on the eyes looking):

scope a,      -> { where(a) }scope b,      -> { where(b) }scope a_or_b, -> { a.or(b) }