Skip to content

Commit

Permalink
Add documentation for find_or_create_by_{attribute}! method.
Browse files Browse the repository at this point in the history
  • Loading branch information
pixeltrix committed Mar 12, 2012
1 parent 90d9635 commit a01f0ab
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
3 changes: 3 additions & 0 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -208,6 +208,9 @@ module ActiveRecord #:nodoc:
# # Now 'Bob' exist and is an 'admin'
# User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
#
# Adding an exclamation point (!) on to the end of <tt>find_or_create_by_</tt> will
# raise an <tt>ActiveRecord::RecordInvalid</tt> error if the new record is invalid.
#
# Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
# saving it first. Protected attributes won't be set unless they are given in a block.
#
Expand Down
2 changes: 2 additions & 0 deletions railties/guides/source/active_record_querying.textile
Expand Up @@ -1109,6 +1109,8 @@ Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
</ruby>

As with +first_or_create+ there is a +find_or_create_by!+ method but the +first_or_create!+ method is preferred for clarity.

h4. +first_or_initialize+

The +first_or_initialize+ method will work just like +first_or_create+ but it will not call +create+ but +new+. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the +first_or_create+ example, we now want the client named 'Nick':
Expand Down

0 comments on commit a01f0ab

Please sign in to comment.