Rails 5: Meet the Active Record OR Query

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?

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.

Victor A.M.

Victor A.M.
Yet another passionate web developer, mostly experienced with Ruby on Rails and Vue.js.
Currently living in São Paulo and working at Plataformatec.

Vue.js Advanced: Mastering Events

In this post we will take a deep dive into the Vue.js event system, talking about the good practices, helpful tricks and common pitfalls that you will can face. Continue reading

Ruby object interfaces: Public x Private

Published on April 24, 2016

Rails transactions: The Complete Guide

Published on April 17, 2016