From fcf31cb7521ba7de0aae972ac2ddfc80e3e7dfce Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 7 Sep 2008 14:42:33 +0100 Subject: Support for updating a belongs to association from the foreign key (without saving and reloading the record) Signed-off-by: Michael Koziarski [#142 state:committed] --- activerecord/lib/active_record/associations.rb | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/associations.rb') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index aca2d770fc..5d91315aad 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1237,7 +1237,7 @@ module ActiveRecord association = instance_variable_get(ivar) if instance_variable_defined?(ivar) - if association.nil? || force_reload + if association.nil? || !association.loaded? || force_reload association = association_proxy_class.new(self, reflection) retval = association.reload if retval.nil? and association_proxy_class == BelongsToAssociation @@ -1266,6 +1266,13 @@ module ActiveRecord end end + if association_proxy_class == BelongsToAssociation + define_method("#{reflection.primary_key_name}=") do |target_id| + instance_variable_get(ivar).reset if instance_variable_defined?(ivar) + write_attribute(reflection.primary_key_name, target_id) + end + end + define_method("set_#{reflection.name}_target") do |target| return if target.nil? and association_proxy_class == BelongsToAssociation association = association_proxy_class.new(self, reflection) -- cgit v1.2.3