Permalink
Browse files

Avoid an attempt to fetch old record when id was not present in touch…

… callback
  • Loading branch information...
1 parent 034f254 commit dce398d579e484ff64a0260cea4591ad952dc99c @carlosantoniodasilva carlosantoniodasilva committed Apr 5, 2013
Showing with 7 additions and 7 deletions.
  1. +7 −7 activerecord/lib/active_record/associations/builder/belongs_to.rb
View
14 activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -66,19 +66,19 @@ def belongs_to_counter_cache_after_update_for_#{name}
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

0 comments on commit dce398d

Please sign in to comment.