I’ve noticed that the Model.where method always returns an array even if there is only one result where as the Model.find method doesn’t. Is there any reason for this? I thought Model.where was the preferred function since Rails 3.X.
Should I be using Model.find when I expect a single result and Model.where when I expect more than one result?
wherereturns anActiveRecord::Relation(not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation.find(and its related dynamicfind_by_columnnamemethods) returns a single model object. If nothing is found, anActiveRecord::RecordNotFoundexception is raised (but not with the dynamicfind_by_methods).While
findcan return an Array of records—not a Relation—if given a list of IDs, usingwhereis preferred since Rails 3. Many similar uses offindare now deprecated or gone entirely.So yes, if you only want and expect a single object, using
findis easier, as otherwise you must callModel.where.first.Note that old-style hash options to
findand many dynamicfind_methods are deprecated as of Rails 4.0 (see relevant release notes).