0
0

More than 1 year has passed since last update.

【Rails】find_or_initialize_byとfind_or_create_byの違い

Last updated at Posted at 2022-02-25

find_or_create_by

条件を指定して初めの1件を取得(find)し、1件もなければ作成(create)
作成する時に呼ぶメソッドがcreateなので、新規作成して保存まで行う

Category.find_or_create_by!(name: "ディナー")
  Category Load (0.6ms)  SELECT "categories".* FROM "categories" WHERE "categories"."name" = $1 LIMIT $2  [["name", "ディナー"], ["LIMIT", 1]]
  TRANSACTION (0.5ms)  BEGIN
  Category Create (2.0ms)  INSERT INTO "categories" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["name", "ディナー"], ["created_at", "2022-02-21 12:19:12.868048"], ["updated_at", "2022-02-21 12:19:12.868048"]]
  TRANSACTION (1.4ms)  COMMIT
=> #<Category:0x00007fed472719b0 id: 1, name: "ディナー", created_at: Mon, 21 Feb 2022 12:19:12.868048000 JST +09:00, updated_at: Mon, 21 Feb 2022 12:19:12.868048000 JST +09:00>
Category.find_or_create_by!(name: "その他")
  Category Load (0.6ms)  SELECT "categories".* FROM "categories" WHERE "categories"."name" = $1 LIMIT $2  [["name", "その他"], ["LIMIT", 1]]
=> #<Category:0x00007fed4483f0e8 id: 2, name: "その他", created_at: Thu, 03 Feb 2022 12:20:21.014342000 JST +09:00, updated_at: Thu, 03 Feb 2022 12:20:21.014342000 JST +09:00>

find_or_initialize_by

条件を指定して初めの1件を取得(find)し、1件もなければ作成(new)
作成する時に呼ぶメソッドがnewなので、保存はしない

参考

0
0
0

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
0
0