Rails 5: ActiveRecord OR query

K M Rakibul Islam picture K M Rakibul Islam · Sep 24, 2015 · Viewed 43.8k times · Source

How do you do an or query in Rails 5 ActiveRecord? Also, is it possible to chain or with where in ActiveRecord queries?

Answer

K M Rakibul Islam picture K M Rakibul Islam · Sep 24, 2015

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)