From dce398d579e484ff64a0260cea4591ad952dc99c Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Thu, 4 Apr 2013 22:22:42 -0300 Subject: [PATCH] Avoid an attempt to fetch old record when id was not present in touch callback --- .../associations/builder/belongs_to.rb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index e0ec4392b4a..3ba6a713662 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -66,19 +66,19 @@ module ActiveRecord::Associations::Builder def add_touch_callbacks(reflection) mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 def belongs_to_touch_after_save_or_destroy_for_#{name} - record = #{name} + foreign_key_field = #{reflection.foreign_key.inspect} + old_foreign_id = attribute_was(foreign_key_field) + + if old_foreign_id + reflection_klass = #{reflection.klass} + old_record = reflection_klass.find_by(reflection_klass.primary_key => old_foreign_id) - foreign_key_field = #{reflection.foreign_key.inspect} - if changed_attributes.key?(foreign_key_field) - reflection_klass = #{reflection.klass} - primary_key_field = reflection_klass.primary_key - old_foreign_id = changed_attributes[foreign_key_field] - old_record = reflection_klass.where(primary_key_field => old_foreign_id).first if old_record old_record.touch #{options[:touch].inspect if options[:touch] != true} end end + record = #{name} unless record.nil? || record.new_record? record.touch #{options[:touch].inspect if options[:touch] != true} end