0

Possible Duplicate:
Rails “find_all_by” vs “.where”

In this piece of code

I was wondering what the difference between line 1 and 2.

The COLUMN_NAME is either nil, or unique value.

   def get_row
     id = "someidhere"
1    r = Model.find_by_COLUMN_NAME(id)
2    r = Model.where('COLUMN_NAME = ? ', id).first
     if !r.nil?
     r
     else
       nil
     end
   end

Is 2 more explicit than 1? What are some side effects that I should watch out for? (If id was nil, or searching for non existing id)

I was using find_by_COLUMN_NAME before and I was getting unexpected results.

When the function returns, I am calling r.id.to_s where r should be an instance of Model, however, sometimes I am getting the value 2 from nowhere.

Community
  • 1
  • 1
Bill
  • 3,059
  • 3
  • 31
  • 47

1 Answers1

2

.where methods return an ActiveRecord relation, which means they can be chained with other such methods and scopes, as in Model.where(:user_id => id).published. The dynamic finders (.find_by_name, etc.), return model instances or arrays, which cannot be chained with additional scopes.

Dynamic finders can return an ActiveRecord::RecordNotFound error when the expected record is not found (rather than nil, [], or an empty relation) if used with an exclamation point, e.g. User.find_by_email!('example@email.com)`.

They each have their own uses; it's up to you to decide based on the cases in which your method would be called.

Zach Kemp
  • 11,736
  • 1
  • 32
  • 46