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?

Upvotes: 16

Views: 20535

Answers (2)

Flavio Wuensche
Flavio Wuensche

Reputation: 10336

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.

Upvotes: 19

BlueFish
BlueFish

Reputation: 5135

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

Upvotes: 6

Related Questions