I know there are 3 main notations for supplying arguments to the where
ActiveRecord method:
Specifying and
for the where
method is straight forward:
# Pure String notation Person.where("name = 'Neil' AND age = 27") # Array notation Person.where(["name = ? AND age = ?", 'Neil', 27]) # Hash notation 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 Person.where("name = 'Neil' OR age = 27") # Array notation Person.where(["name = ? OR age = ?", 'Neil', 27]) # Hash notation DOESN'T WORK Person.where({name: "Neil" OR age: 27})
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
Active Model is a library containing various modules used in developing classes that need some features present on Active Record.
The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash-ish):
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))
Use where_values
together with 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) )
Install third-party plugins that implement these or similar features, for example:
Where Or (backport of the Ruby on Rails 5 .or
feature mentioned above)
Squeel
Person.where{(name == 'Neil') | (age == 27)}
RailsOr
Person.where(name: 'Neil').or(age: 27)
ActiverecordAnyOf
Person.where.anyof(name: 'Neil', age: 27)
SmartTuple
Person.where( (SmartTuple.new(' or ') << {name: 'Neil', age: 27}).compile )
Use Arel:
Person.where( Person.arel_table[:name].eq('Neil').or( Person.arel_table[:age].eq(27) ) )
Use prepared statements with named parameters:
Person.where('name = :name or age = :age', name: 'Neil', age: 27)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With