Neil Neil - 1 year ago 94
Ruby Question

ActiveRecord OR query Hash notation

I know there are three main types of notations for supplying conditions in the

ActiveRecord method:

  1. Pure String

  2. Array

  3. Hash

for the
method is straight forward:

# Pure String notation
@people= Person.where("name = 'Neil' AND age = 27")

# Array notation
@people = Person.where(["name = ? AND age = ?", 'Neil', 27])

# Hash notation
@people = Person.where({name: "Neil", age: 27})

for this same
method is stumping me for the hash syntax. Is it possible?

# Pure String notation
@people= Person.where("name = 'Neil' OR age = 27")

# Array notation
@people = Person.where(["name = ? OR age = ?", 'Neil', 27])

# Hash notation DOESN'T WORK
@people = Person.where({name: "Neil" OR age: 27})

Answer Source

There are 5 options that can be considered as implementations of «Hash notation» approach (the last is kinda hash-ish). You can:

  1. With Ruby on Rails 5 you are able to do the following chaining using ActiveRecord::Relation#or method:

    Person.where(name: 'Neil').or( Person.where(age: 27) )
  2. With Ruby on Rails 4.2+ you can use Where Or gem, which is a third-party backport of the Ruby on Rails 5 .or feature mentioned above.

  3. Use where_values together with inject or reduce. The unscoped method is necessary only for Rails 4.1+ to ensure default_scope is not included in the where_values. Otherwise predicates from both default_scope and where would be chained with the or operator:

      Person.unscoped.where(name: ['Neil'], age: [27]).where_values.reduce(:or) 
  4. Install third-party plugins that implement these or similar features, for example:

    • Squeel:

      Person.where{(name == 'Neil') | (age == 27)} 
    • ActiverecordAnyOf:

      Person.where.anyof(name: 'Neil', age: 27)
    • SmartTuple:

        (' or ') << {name: 'Neil', age: 27}).compile
  5. Use Arel:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download