Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adding inline documentation for first_or_create and first_or_create!

Related to #2420.
  • Loading branch information...
commit 7b90e44228d039370df049b48f5894da053e6a10 1 parent c9ac222
@andmej authored
Showing with 27 additions and 0 deletions.
  1. +27 −0 activerecord/lib/active_record/relation.rb
View
27 activerecord/lib/active_record/relation.rb
@@ -94,10 +94,37 @@ def create!(*args, &block)
scoping { @klass.create!(*args, &block) }
end
+ # Tries to load the first record; if it fails, then <tt>create</tt> is called with the same arguments as this method.
+ #
+ # Expects arguments in the same format as <tt>Base.create</tt>.
+ #
+ # ==== Examples
+ # # Find the first user named Scarlett or create a new one.
+ # User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
+ # # => <User id: 1, first_name: 'Scarlett', last_name: 'Johansson'>
+ #
+ # # Find the first user named Scarlett or create one with a different last name.
+ # # We already have one Scarlett, so she'll be returned.
+ # User.where(:first_name => 'Scarlett').first_or_create do |user|
+ # user.last_name = "O'Hara"
+ # end
+ # # => <User id: 1, first_name: 'Scarlett', last_name: 'Johansson'>
+ #
+ # # Find the first user named Andy or create several at a time.
+ # User.where(:first_name => 'Andy').first_or_create([{:last_name => 'García'}, {:last_name => 'Mejía'}])
+ # # => [#<User id: 2, first_name: 'Andy', last_name: 'García'>,
+ # #<User id: 3, first_name: 'Andy', last_name: 'Mejía'>]
+ #
+ # # Find the first user with last name García or create several at a time.
+ # User.where(:last_name => 'García').first_or_create([{:first_name => 'Jorge'}, {:first_name => 'Andy'}])
+ # # => <User id: 2, first_name: 'Andy', last_name: 'García'>
def first_or_create(*args, &block)
first || create(*args, &block)
end
+ # Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
+ #
+ # Expects arguments in the same format as <tt>Base.create</tt>.
def first_or_create!(*args, &block)
first || create!(*args, &block)
end
Please sign in to comment.
Something went wrong with that request. Please try again.