Read more

OR-ing query conditions on Rails 4 and 3.2

Arne Hartherz
September 29, 2015Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2015-09-29 12:12)