From 4168f876238982d0d584006f50188071928a8b7f Mon Sep 17 00:00:00 2001 From: Luciano G Panaro Date: Sat, 26 Sep 2009 10:33:50 -0300 Subject: Make has_one with :conditions hash scope build or creation of the associated object with those conditions Signed-off-by: Michael Koziarski [#3088 state:committed] --- activerecord/lib/active_record/associations.rb | 4 +++- .../lib/active_record/associations/has_one_association.rb | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 266a52d612..497115e4ff 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -938,7 +938,9 @@ module ActiveRecord # if the real class name is Person, you'll have to specify it with this option. # [:conditions] # Specify the conditions that the associated object must meet in order to be included as a +WHERE+ - # SQL fragment, such as rank = 5. + # SQL fragment, such as rank = 5. Record creation from the association is scoped if a hash + # is used. has_one :account, :conditions => {:enabled => true} will create an enabled account with @company.create_account + # or @company.build_account. # [:order] # Specify the order in which the associated objects are returned as an ORDER BY SQL fragment, # such as last_name, first_name DESC. diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index c2568d0c0c..b85a40b2e5 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -8,18 +8,21 @@ module ActiveRecord def create(attrs = {}, replace_existing = true) new_record(replace_existing) do |reflection| + attrs = merge_with_conditions(attrs) reflection.create_association(attrs) end end def create!(attrs = {}, replace_existing = true) new_record(replace_existing) do |reflection| + attrs = merge_with_conditions(attrs) reflection.create_association!(attrs) end end def build(attrs = {}, replace_existing = true) new_record(replace_existing) do |reflection| + attrs = merge_with_conditions(attrs) reflection.build_association(attrs) end end @@ -128,6 +131,12 @@ module ActiveRecord inverse = @reflection.inverse_of return !inverse.nil? end + + def merge_with_conditions(attrs={}) + attrs ||= {} + attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash) + attrs + end end end end -- cgit v1.2.3