I'm new to rails. Just wondering which is the better approach that will return nil if the subject_id can't be found:
@subject = Subject.find_by_id(params[:subject_id])
or
@subject = Subject.where(:id => params[:subject_id]).first
Thanks.
Join Stack Overflow to learn, share knowledge, and build your career.
I'm new to rails. Just wondering which is the better approach that will return nil if the subject_id can't be found:
@subject = Subject.find_by_id(params[:subject_id])
or
@subject = Subject.where(:id => params[:subject_id]).first
Thanks.
They both generate the same SQL statement:
1.9.3p194 :003 > Example.find_by_id(9)
Example Load (0.3ms) SELECT "examples".* FROM "examples" WHERE "examples"."id" = 9 LIMIT 1
nil
1.9.3p194 :004 > Example.where(:id => 9).first
Example Load (0.3ms) SELECT "examples".* FROM "examples" WHERE "examples"."id" = 9 LIMIT 1
nil
So they'll have the same performance characteristics at the database. There may be a slight difference in the Rails code for find_by_*_
vs. where
, but I'd imagine that will be negligible compared to query time.
Edit: In light of Ryan Bigg's comment below, I'd have to suggest the second form for forward compatibility.
find_by_id
: edgeguides.rubyonrails.org/…
– Aaron Jensen
Nov 8 '13 at 16:35
I prefer find_by
as the name is descriptive and you get the object with out having to call a second function (i.e. first
)
User.find(9) # returns User object. Throws exception when not found.
User.find_by(id: 9) # returns User object. Returns nil when not found.
User.where(id: 9).first # returns User object. Returns nil when not found.