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

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.


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