LoginSignup
1

More than 5 years have passed since last update.

Railsのfindとwhere(id: XXX).firstの違い

Posted at

findとwhere(id: XXX).firstの違い

両方ともidで絞り込みをかけるがその他の挙動が違う箇所が多いのでメモ

find

  • 返り値はレシーバーのオブジェクト
  • DB問い合わせを行う
  • 発行SQLにorder by id descが付与されない
$ User.find(1).class
User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
=> User

where

  • 返り値はActiveRecord_Relationのオブジェクト
  • where().firstwhere().map()などデータを操作するタイミングでDB問い合わせを行う
  • 発行SQLにORDER BY "users"."id" ASCが付与される
$ User.where(id: 1).class
=> User::ActiveRecord_Relation

$ User.where(id: 1).first
User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
=> #<User:0x00007fffcb3d3e98

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1