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