提交 7160ffbe 编写于 作者: R Rafael Mendonça França

Merge pull request #12621 from laurocaetano/fix_has_one_association_with_primary_key_set

Save association when primary key is manually set

Conflicts:
	activerecord/CHANGELOG.md
* 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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册