From 8022fc4913d5fa285889795617a1f37c5aa705a9 Mon Sep 17 00:00:00 2001 From: laurocaetano Date: Thu, 24 Oct 2013 00:06:49 -0200 Subject: Save association when primary key is manually set --- activerecord/lib/active_record/autosave_association.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 561b2dd6d1..e9622ca0c1 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -384,7 +384,8 @@ module ActiveRecord record.destroy else key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id - if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave) + if autosave != false && (autosave || new_record? || record_changed?(reflection, record, key)) + unless reflection.through_reflection record[reflection.foreign_key] = key end @@ -397,6 +398,11 @@ module ActiveRecord end end + # If the record is new or it has changed, returns true. + def record_changed?(reflection, record, key) + record.new_record? || record[reflection.foreign_key] != key || record.attribute_changed?(reflection.foreign_key) + end + # Saves the associated record if it's new or :autosave is enabled. # # In addition, it will destroy the association if it was marked for destruction. -- cgit v1.2.3