diff options
Diffstat (limited to 'activerecord/lib/active_record/associations/builder/belongs_to.rb')
-rw-r--r-- | activerecord/lib/active_record/associations/builder/belongs_to.rb | 20 |
1 files changed, 16 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb index 9ac561b997..543a0247d1 100644 --- a/activerecord/lib/active_record/associations/builder/belongs_to.rb +++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb @@ -25,9 +25,10 @@ module ActiveRecord::Associations::Builder mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 def belongs_to_counter_cache_after_create_for_#{name} - record = #{name} - record.class.increment_counter(:#{cache_column}, record.id) unless record.nil? - @_after_create_counter_called = true + if record = #{name} + record.class.increment_counter(:#{cache_column}, record.id) + @_after_create_counter_called = true + end end def belongs_to_counter_cache_before_destroy_for_#{name} @@ -66,8 +67,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 + klass = association(#{name.inspect}).klass + old_record = klass.find_by(klass.primary_key => old_foreign_id) + 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 |