Rails 5: Meet the Active Record OR Query
How many nights did you spend crying for all those Arel queries you had to write to attain a simple OR query in Rails? Well those times of suffering are over, give a warm welcome to the Rails 5 ActiveRecord OR query method!
It’s actually very simple to use but does have some caveats that we will see in a moment.
How to use it?
The .or method works like this:
User.where(id: 1).or(User.where(name: "Flynn"))
Pretty simple, huh?
Using joins with OR
There is a requirement when you use the Rails 5 .or method: both sides of the query must have a compatible structure. What does it mean?
1 2 3 4 5
User.joins(:profile).where(name: "John").or(User.where(name: "Tom")).count # => ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins] User.joins(:profile).where(name: "John").or(User.joins(:profile).where(name: "Tom")).count # => 2
Oh, this also happens with
.includes as you probably imagined.
In fact, the only difference that can exist between both sides of the OR are the WHERE and HAVING clauses. Any other difference will throw out an ArgumentError claiming an incompatible structure.
Not on Rails 5 yet? There is still hope
This gem (Eric-Guo/where-or) implement the where.or method in Rails 4.2+ for the people not ready yet to jump aboard the 5th version train.
It is simple a port from the Rails 5 implementation so it should be fairly safe to use in your projects.