Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to find the first record in Rails (ActiveRecord)?

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?

like image 861
Jérôme Boé Avatar asked Aug 27 '12 02:08

Jérôme Boé


People also ask

What is ActiveRecord in Ruby on Rails?

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.

What is ActiveRecord relation?

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.

What is ActiveRecord ORM?

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.

What is ActiveRecord implementation?

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.


2 Answers

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 from first in regards to the order of your records. first will return the first record according to the order of the primary key while take will just return whatever the database spits out first.

So while using where().take is equivalent to find_by and choosing whether to use one of the other is a matter of taste, where().first differs from find_by in a subtle and not so obvious way.

like image 82
Flavio Wuensche Avatar answered Oct 20 '22 07:10

Flavio Wuensche


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
like image 41
BlueFish Avatar answered Oct 20 '22 08:10

BlueFish