aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/querying.rb1
-rw-r--r--activerecord/lib/active_record/relation.rb26
2 files changed, 27 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb
index 13e09eda53..45f6a78428 100644
--- a/activerecord/lib/active_record/querying.rb
+++ b/activerecord/lib/active_record/querying.rb
@@ -3,6 +3,7 @@ module ActiveRecord
module Querying
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all
delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all
+ delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :to => :all
delegate :find_by, :find_by!, :to => :all
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all
delegate :find_each, :find_in_batches, :to => :all
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.