ActiveRecord: Query one column for multiple values

06 Nov 2019

I keep discovering things in ActiveRecord way after they’re released. I recently had to perform a query where I wanted everything where one single column had one of two values.

In Rails 5 I believe it was, the following was added:

User.where(role: 'admin').or(User.where(role: 'staff'))

This is good in the case where you want to chain a bunch of different things - but as a single query on the same column I’m not necessarily a fan of this style.

I discovered that you can simply pass an array to the where clause which will produce an IN SQL query:

User.where(role: ['admin', 'staff'])
# => SELECT "users".* FROM "users" WHERE "users"."role" IN ($1, $2) LIMIT $3  [["role", "admin"], ["role", "staff"], ["LIMIT", 11]]

Simple but powerful stuff!