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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They both generate the same SQL statement:
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.