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.
The principal advantage with the
.wheremethod 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.whereis 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:
Update
I tried and compared the 2 following in my IRB console (~620 records in the DB)
It produces the same query, and takes the same execution time.