marcamillion
marcamillion

Reputation: 33755

Which is faster `Model.where(:attribute)` or `Model.find_by_attribute_id(id)`?

I have a model called Max.

Which will be a faster way to find this record:

Assume that user is a local variable already set.

Max.where(:user_id => user.id)

or

Max.find_by_user_id(user.id)

Assume that this query will be run frequently, and there is an index for the user_id column on the Maxes table.

Is there any benefit to going one way or another? i.e. one produces less queries but runs slower or vice versa?

Thanks.

Upvotes: 0

Views: 1189

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

The principal advantage with the .where method is that is returns an ActiveRecord::Relation (acts like an array, can be empty if no record match the conditions given). The other big advantage of .where is that you can chain them, very usefull for scopes!

With the .find, it returns the Object or raise an ActiveRecord::RecordNotFound error.


So imagine you have no user matching the id you're passing:

Max.find(-1) # => Raise ActiveRecord::RecordNotFound: Couldn't find Project with ID=-1

Max.where(id: -1) # => Returns an empty ActiveRecord::Relation, doesn't raise an error

Update

I tried and compared the 2 following in my IRB console (~620 records in the DB)

User.find(User.all.map(&:id))
User.where(id: User.all.map(&:id))

It produces the same query, and takes the same execution time.

Upvotes: 4

Tom Harrison
Tom Harrison

Reputation: 14018

Notwithstanding the miniscule bit of ruby code that needs to run, they are identical.

Check your development log. They generate the same SQL.

I prefer the new AREL form -- it's much more general, only executes when needed, and chainable.

Upvotes: 2

Related Questions