I would like to know which method is fastest for return a record.
Class.where(:type => 4).first
Class.find(:first, :conditions => ["type = ?", 4])
Is the execution exactly the same?
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.
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.
Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows − tables map to classes, rows map to objects and. columns map to object attributes.
Active Record Implementation is an architectural pattern found in software engineering that stores in-memory object data in relational databases. Active Record facilitates the creation and use of business objects whose data is required to persistent in the database.
The most performant, assuming you don't care about the order, is to use find_by
:
Class.find_by(type: 4)
From https://github.com/rubocop-hq/rails-style-guide/issues/76
This method has been added on Rails 4 and it is defined like this:
def find_by(*args) where(*args).take end
So,
take
differs fromfirst
in regards to the order of your records.first
will return the first record according to the order of the primary key whiletake
will just return whatever the database spits out first.So while using
where().take
is equivalent tofind_by
and choosing whether to use one of the other is a matter of taste,where().first
differs fromfind_by
in a subtle and not so obvious way.
Both would produce the same query.
According to the latest information, under Rails 3.1, passing in :conditions will be deprecated.
Hence, right now, the best way to execute the query is to use:
Class.where(:type => 4).first
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