2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby on Rails レコード検索、無ければ作成 find_or_create_by メソッド

Posted at

find_or_create_by メソッドとは?

find_or_create_by メソッドとは、findメソッドとcreateメソッドが合わさったメソッドであり、
引数に渡した条件に該当するレコードをテーブルから検索し
該当するレコードがあれば取得、無ければ作成してくれるメソッド。

使い方

モデル.find_or_create_by(検索条件)

例:usersテーブルの中からnameが"suzuki"のレコードを取得、無ければ作成する場合

User.find_or_create_by(name: "suzuki")
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?