find_or_create_by

検索条件を指定して初めの1件を取得し、1件もなければ作成(find_or_create_by)

適応バージョン

  • 1.0.0
  • 1.1.0
  • 1.1.1
  • 1.1.6
  • 1.2.0
  • 1.2.6
  • 2.0.0
  • 2.0.1
  • 2.0.3
  • 2.1.0
  • 2.2.1
  • 2.3.2
  • 2.3.8
  • 3.0.0
  • 3.0.5
  • 3.0.7
  • 3.0.9
  • 3.1.0
  • 3.2.3
  • 3.2.8
  • 3.2.13
  • 4.0.0
  • 4.1.0
  • 4.2.1

説明

検索条件を指定して初めの1件を取得し、1件もなければ作成する

使い方

モデル.find_or_create_by(条件)

# Find the first user named Penélope or create a new one.
User.find_or_create_by(first_name: 'Penélope')
# => <User id: 1, first_name: 'Penélope', last_name: nil>

# Find the first user named Penélope or create a new one.
# We already have one so the existing record will be returned.
User.find_or_create_by(first_name: 'Penélope')
# => <User id: 1, first_name: 'Penélope', last_name: nil>

# Find the first user named Scarlett or create a new one with a particular last name.
User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

# Find the first user named Scarlett or create a new one with a different last name.
# We already have one so the existing record will be returned.
User.find_or_create_by(first_name: 'Scarlett') do |user|
  user.last_name = "O'Hara"
end
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>

ソースコード

ソースコード検索