プログラミング学習記録ブログ

ちなみに、外国人なので、日本語が少しおかしいかも、、すみません

Railsにおける、findとwhereの違い

 showupdateなど、よく使われる.findなんですが、最近.whereというメソッドの存在を知りました。
 使ってみたら、.whereのほうが配列としてreturnしてくるが、.findならそうreturnしてこないらしい。。。。これで、複数のデータなら.where、個別なら.findでいいのかな?と思い、ネットで調べてみたら、違いはありました。。(今までの憶測はなんだろう=)

  • where returns an ActiveRecord::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 dynamic find_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, an ActiveRecord::RecordNotFound exception is raised.

 確かに、この場合だと、個別なら.findの方が良いですよね。。ふーむ