Nick5a1
Nick5a1

Reputation: 917

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.

Upvotes: 6

Views: 11950

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

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.

Upvotes: 9

Brandan
Brandan

Reputation: 14983

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.

Upvotes: 4

Related Questions