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 =

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.)

Think your friends would dig this article, too?

If you need a mobile app built for your business or your idea, there's a chance I could help you with that.
Leave your email here and I will get back to you shortly.