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