LoginSignup
0
0

find_or_create_by について

Posted at

find_or_create_by とは

ActiveRecordが用意しているメソッド
存在チェックをしながら、登録ができる
また、該当のレコードが見つかった場合は、該当のレコードが戻り値として返ってくる

user = User.find_or_create_by!(name: "Alice")
 →nameカラムがAliceのレコードを検索し、該当するものがなかった場合登録をする

find_or_create_by と find_or_create_by! の違い

find_or_create_by は登録ができなかった場合はnilを返し、例外は発生しない
find_or_create_by! は登録ができなかった場合は、例外を発生させる

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