LoginSignup
7
6

More than 3 years have passed since last update.

「find_or_create_by」と「create_or_find_by」 の違い #Railsのコードを読んでみた

Last updated at Posted at 2019-06-21

これ何

create_or_find_byfind_or_create_by の違いってなんだろうって深夜に思ったのでまとめました。

まとめ

簡単にまとめると、createが先に実行されるかfindが先に実行されるかです。

create_or_find_by

transactionに失敗したらfind_byする。

def create_or_find_by(attributes, &block)
  transaction(requires_new: true) { create(attributes, &block) }
rescue ActiveRecord::RecordNotUnique
  find_by!(attributes)
end

Railsのコード

違いについて

find_or_create_by でできないカラムもcreate_or_find_byではできてしまう可能性があります。

例えば、Userモデルがあったとします。create_or_find_by ではcreateが先に実行されるため2つ同じようなデータが作られます。
find_or_create_byでは、findが先に実行されるため、検索結果が返され、同じデータは2つ作られることはありません。

User.create_or_find_by({name: 'geru')
User.create_or_find_by({name: 'geru')
User.count
# => 2
User.find_or_create_by({name: 'geru')
User.find_or_create_by({name: 'geru')
User.count
# => 1

関連

find_or_initialize_byとfind_or_create_byの違い

7
6
2

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