Permalink
Browse files

Save association when primary key is manually set

  • Loading branch information...
1 parent cc8d148 commit 8022fc4913d5fa285889795617a1f37c5aa705a9 @laurocaetano laurocaetano committed Oct 24, 2013
@@ -1,3 +1,9 @@
+* Save `has_one` association when primary key is manually set.
+
+ Fixes #12302
+
+ *Lauro Caetano*
+
* Make `Relation#empty?` use `exists?` instead of `count`.
*Szymon Nowak*
@@ -384,7 +384,8 @@ def save_has_one_association(reflection)
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 @@ def save_has_one_association(reflection)
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 <tt>:autosave</tt> is enabled.
#
# In addition, it will destroy the association if it was marked for destruction.
@@ -524,4 +524,15 @@ def test_has_one_assignment_triggers_save_on_change
assert_equal 'new name', pirate.ship.reload.name
end
+ def test_has_one_autosave_with_primary_key_manually_set
+ post = Post.create(id: 1234, title: "Some title", body: 'Some content')
+ author = Author.new(id: 33, name: 'Hank Moody')
+
+ author.post = post
+ author.save
+ author.reload
+
+ assert_not_nil author.post
+ assert_equal author.post, post
+ end
end

0 comments on commit 8022fc4

Please sign in to comment.