Neil Neil - 4 months ago 21
Ruby Question

ActiveRecord OR query Hash notation

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

where
ActiveRecord method:


  1. Pure String

  2. Array

  3. Hash



Specifying
and
for the
where
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})


Specifying
or
for this same
where
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

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.where( 
      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:

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

    Person.where( 
      Person.arel_table[:name].eq('Neil').or(
      Person.arel_table[:age].eq(27)) 
    )