How to accomplish OR operator with Rails 4 (and lower) query?

15 Feb 2016

You’re building your shiny new application and are getting past super-simple CRUD. You know how to query models when several conditions need to be true at the same time. But what about when you have two conditions and want to query models that match either of them, without going bare SQL?

Rails 5 is getting built-in capability of OR querying… but if you are running previous versions, what do you do?

Suppose we have a booking application and we want to get reservations which either start or end on a given day. Here’s what we’d do:

date = Date.today

res = Reservation.arel_table
checkin = res[:checkin].eq(date)
checkout = res[:checkout].eq(date)
Reservation.where(checkin.or(checkout)) # => [ ... ]

The solution isn’t the prettiest, but what important is, it works. It is using the Arel library, which ActiveRecord uses itself to create queries, but which you can also leverage yourself when your requirements are more complex than what ActiveRecord supports.

(The other option would be SQL queries but these are prone to injections.)

Want to level up your React skills?

Sign up below and I'll send you content just like this about React straight to your inbox every week.

No spam, promise. I hate it as much as you do!

, enjoying the article? Now think of 3 friends who are interested in Rails and would be into it, and share the link with them! 👇

http://goshakkk.name/rails-activerecord-query-or/