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

ruby-on-rails, ruby-on-rails-3.2

Solution

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.

Problem

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.

Original source