Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_by_id(params[:subject_id]) vs where(:id => params[:subject_id]).first

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.

like image 495
Nick5a1 Avatar asked Jun 25 '12 23:06

Nick5a1


2 Answers

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.
like image 68
Harish Shetty Avatar answered Nov 05 '22 10:11

Harish Shetty


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.

like image 22
Brandan Avatar answered Nov 05 '22 09:11

Brandan