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 professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)