Permalink
Browse files

Merge pull request #12621 from laurocaetano/fix_has_one_association_w…

…ith_primary_key_set

Save association when primary key is manually set

Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
2 parents a53f716 + 8022fc4 commit 7160ffbe59ef99f01f530ad6e8377f8a91218396 @rafaelfranca rafaelfranca committed Oct 25, 2013
@@ -1,3 +1,9 @@
+* Save `has_one` association when primary key is manually set.
+
+ Fixes #12302.
+
+ *Lauro Caetano*
+
* Allow any version of BCrypt when using `has_secury_password`.
*Mike Perham*
@@ -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 7160ffb

Please sign in to comment.