OR-ing query conditions on Rails 4 and 3.2

Updated . Posted . Visible to the public.

Rails 5 will introduce ActiveRecord::Relation#or. On Rails 4 and 3.2 you can use the activerecord_any_of Show archive.org snapshot gem which seems to be free of ugly hacks and nicely does what you need.

Use it like this:

User.where.any_of(name: 'Alice', gender: 'female')

^
SELECT "users".* FROM "users" WHERE (("users"."name" = 'Alice' OR "users"."gender" = 'female'))

To group conditions, wrap them in hashes:

User.where.any_of({ name: 'Alice', gender: 'female' }, { name: 'Bob' }, { name: 'Charlie' })

^
SELECT "users".* FROM "users" WHERE ((("users"."name" = 'Alice' AND "users"."gender" = 'female' OR "users"."name" = 'Bob') OR "users"."name" = 'Charlie'))

It also brings none_of which will do the inverse.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-09-29 10:12)