aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation.rb
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2012-10-19 13:18:47 +0100
committerJon Leighton <j@jonathanleighton.com>2012-10-19 13:18:47 +0100
commiteb72e62c3042c0df989d951b1d12291395ebdb8e (patch)
tree258c2dc61b2e146fb2cdef47d2799ea9dbdaa004 /activerecord/lib/active_record/relation.rb
parent0d7b0f0183ce9f1bfc524cf6afd5d7de852ebc76 (diff)
downloadrails-eb72e62c3042c0df989d951b1d12291395ebdb8e.tar.gz
rails-eb72e62c3042c0df989d951b1d12291395ebdb8e.tar.bz2
rails-eb72e62c3042c0df989d951b1d12291395ebdb8e.zip
Add Relation#find_or_create_by and friends
This is similar to #first_or_create, but slightly different and a nicer API. See the CHANGELOG/docs in the commit. Fixes #7853
Diffstat (limited to 'activerecord/lib/active_record/relation.rb')
-rw-r--r--activerecord/lib/active_record/relation.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index ecce7c703b..d106fceca2 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -133,6 +133,10 @@ module ActiveRecord
#
# Expects arguments in the same format as +Base.create+.
#
+ # Note that the <tt>create</tt> will execute within the context of this scope, and that may for example
+ # affect the result of queries within callbacks. If you don't want this, use the <tt>find_or_create_by</tt>
+ # method.
+ #
# ==== Examples
# # Find the first user named Penélope or create a new one.
# User.where(:first_name => 'Penélope').first_or_create
@@ -171,6 +175,28 @@ module ActiveRecord
first || new(attributes, &block)
end
+ # Finds the first record with the given attributes, or creates it if one does not exist.
+ #
+ # See also <tt>first_or_create</tt>.
+ #
+ # ==== Examples
+ # # 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>
+ def find_or_create_by(attributes, &block)
+ find_by(attributes) || create(attributes, &block)
+ end
+
+ # Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
+ def find_or_create_by!(attributes, &block)
+ find_by(attributes) || create!(attributes, &block)
+ end
+
+ # Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
+ def find_or_initialize_by(attributes, &block)
+ find_by(attributes) || new(attributes, &block)
+ end
+
# Runs EXPLAIN on the query or queries triggered by this relation and
# returns the result as a string. The string is formatted imitating the
# ones printed by the database shell.