Railsにおける、findとwhereの違い
show
とupdate
など、よく使われる.find
なんですが、最近.where
というメソッドの存在を知りました。
使ってみたら、.where
のほうが配列としてreturnしてくるが、.find
ならそうreturnしてこないらしい。。。。これで、複数のデータなら.where
、個別なら.find
でいいのかな?と思い、ネットで調べてみたら、違いはありました。。(今までの憶測はなんだろう=)
where
returns 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_columnname
methods) returns a single model object, or possibly a collection of model objects in an Array (not a Relation). If nothing is found, anActiveRecord::RecordNotFound
exception is raised.
確かに、この場合だと、個別なら.find
の方が良いですよね。。ふーむ