Rails.where vs .find

I noticed that the Model.where method always returns an array, even if there is only one result when the Model.find method Model.find not work. Is there a reason for this? I thought Model.where was the preferred feature since Rails 3.X.

Should I use Model.find when I expect one result and Model.where when I expect more than one result?

+69
ruby-on-rails ruby-on-rails-3
Mar 05 2018-12-12T00:
source share
3 answers
  • where returns ActiveRecord::Relation (and not an array, although it behaves like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation.

  • find (and its associated dynamic methods find_by_columnname ) returns a single model object. If nothing is found, an ActiveRecord::RecordNotFound exception is ActiveRecord::RecordNotFound (but not with the dynamic find_by_ methods).

    While find can return an array of records, rather than a link - if a list of identifiers is given, using where is preferred with Rails 3. Many similar uses of find now deprecated or gone completely .

So yes, if you only want and expect a single object, it is easier to use find , since otherwise you have to call Model.where.first .

Note that the old-style hash parameters for find and many of the dynamic find_ methods find_ deprecated as Rails 4.0 ( see the corresponding release notes ).

+109
Mar 05 2018-12-12T00:
source share

In fact, find_by gets the model object from where obtained by ActiveRecord::Relation

 def find_by(*args) where(*args).take end 

Source

+12
Jan 25 '14 at 9:41
source share

Model.find uses the primary key column. Therefore, there is always exactly one or no result. Use it when you are looking for one specific item identified by an identifier.

+5
Mar 05 '12 at 22:01
source share



All Articles