instance method
first_or_create
Ruby on Rails 3.2.22.5
Since v3.2.22.5 Last seen in v3.2.22.5Signature
first_or_create(attributes = nil, options = {}, &block)
Tries to load the first record; if it fails, then create is called with the same arguments as this method.
Expects arguments in the same format as Base.create.
Examples
# Find the first user named Penélope or create a new one.
User.where(:first_name => 'Penélope').first_or_create
# => <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.where(:first_name => 'Penélope').first_or_create
# => <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.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <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.where(:first_name => 'Scarlett').first_or_create do |user|
user.last_name = "O'Hara"
end
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
Parameters
-
attributesopt = nil -
optionsopt = {} -
blockblock
Source
# File activerecord/lib/active_record/relation.rb, line 117
def first_or_create(attributes = nil, options = {}, &block)
first || create(attributes, options, &block)
end
Defined in activerecord/lib/active_record/relation.rb line 117
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Relation