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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)