From 90d96353e6dcd962b182e03f53f2214acde00907 Mon Sep 17 00:00:00 2001 From: Andrew White <andyw@pixeltrix.co.uk> Date: Mon, 12 Mar 2012 11:39:19 +0000 Subject: Add dynamic find_or_create_by_{attribute}! method. (cherry picked from commit 5282485d310d1a6ffcf55e4e7f56ab234e16880d) Conflicts: activerecord/CHANGELOG.md activerecord/lib/active_record/dynamic_finder_match.rb --- activerecord/lib/active_record/dynamic_finder_match.rb | 12 ++++++++++++ activerecord/lib/active_record/relation/finder_methods.rb | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/dynamic_finder_match.rb b/activerecord/lib/active_record/dynamic_finder_match.rb index b309df9b1b..80b17a27df 100644 --- a/activerecord/lib/active_record/dynamic_finder_match.rb +++ b/activerecord/lib/active_record/dynamic_finder_match.rb @@ -18,6 +18,10 @@ module ActiveRecord when /^find_by_([_a-zA-Z]\w*)\!$/ bang = true names = $1 + when /^find_or_create_by_([_a-zA-Z]\w*)\!$/ + bang = true + instantiator = :create + names = $1 when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/ instantiator = $1 == 'initialize' ? :new : :create names = $2 @@ -52,5 +56,13 @@ module ActiveRecord def bang? @bang end + + def save_record? + @instantiator == :create + end + + def save_method + bang? ? :save! : :save + end end end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 0305e561c8..9a34927857 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -290,7 +290,7 @@ module ActiveRecord r.assign_attributes(unprotected_attributes_for_create, :without_protection => true) end yield(record) if block_given? - record.save if match.instantiator == :create + record.send(match.save_method) if match.save_record? end record -- cgit v1.2.3