aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/belongs_to_association.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/associations/belongs_to_association.rb')
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb19
1 files changed, 14 insertions, 5 deletions
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index c8716741b0..08f450278d 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -16,7 +16,7 @@ module ActiveRecord
end
end
- def target=(record)
+ def inversed_from(record)
replace_keys(record)
super
end
@@ -42,6 +42,10 @@ module ActiveRecord
update_counters(1)
end
+ def target_changed?
+ owner.saved_change_to_attribute?(reflection.foreign_key)
+ end
+
private
def replace(record)
if record
@@ -53,6 +57,8 @@ module ActiveRecord
decrement_counters
end
+ replace_keys(record)
+
self.target = record
end
@@ -77,19 +83,22 @@ module ActiveRecord
def update_counters_on_replace(record)
if require_counter_update? && different_target?(record)
owner.instance_variable_set :@_after_replace_counter_called, true
- record.increment!(reflection.counter_cache_column)
+ record.increment!(reflection.counter_cache_column, touch: reflection.options[:touch])
decrement_counters
end
end
# Checks whether record is different to the current target, without loading it
def different_target?(record)
- record.id != owner._read_attribute(reflection.foreign_key)
+ record._read_attribute(primary_key(record)) != owner._read_attribute(reflection.foreign_key)
end
def replace_keys(record)
- owner[reflection.foreign_key] = record ?
- record._read_attribute(reflection.association_primary_key(record.class)) : nil
+ owner[reflection.foreign_key] = record ? record._read_attribute(primary_key(record)) : nil
+ end
+
+ def primary_key(record)
+ reflection.association_primary_key(record.class)
end
def foreign_key_present?