mirror of https://github.com/rails/rails
Don't re-assign unchanged belongs_to associations during saves
This commit is contained in:
parent
06a872fd27
commit
2bdee49def
|
@ -501,7 +501,7 @@ module ActiveRecord
|
|||
|
||||
if association.updated?
|
||||
association_id = record.public_send(reflection.options[:primary_key] || :id)
|
||||
self[reflection.foreign_key] = association_id
|
||||
self[reflection.foreign_key] = association_id unless self[reflection.foreign_key] == association_id
|
||||
association.loaded!
|
||||
end
|
||||
|
||||
|
|
|
@ -84,6 +84,10 @@ end
|
|||
|
||||
ActiveRecord.raise_on_assign_to_attr_readonly = previous_value
|
||||
|
||||
class ReadonlyAuthorPost < Post
|
||||
attr_readonly :author_id
|
||||
end
|
||||
|
||||
class Weird < ActiveRecord::Base; end
|
||||
|
||||
class LintTest < ActiveRecord::TestCase
|
||||
|
@ -844,6 +848,33 @@ class BasicsTest < ActiveRecord::TestCase
|
|||
assert_equal "changed via []=", post.body
|
||||
end
|
||||
|
||||
def test_readonly_attributes_on_belongs_to_association
|
||||
assert_equal [ "author_id" ], ReadonlyAuthorPost.readonly_attributes
|
||||
|
||||
author1 = Author.create!(name: "Alex")
|
||||
author2 = Author.create!(name: "Not Alex")
|
||||
|
||||
post_with_reload = ReadonlyAuthorPost.create!(author: author1, title: "Hi", body: "there")
|
||||
post_with_reload.reload
|
||||
post_with_reload.update(title: "Hello", body: "world")
|
||||
assert_equal author1, post_with_reload.author
|
||||
|
||||
post_with_reload2 = ReadonlyAuthorPost.create!(author: author1, title: "Hi", body: "there")
|
||||
post_with_reload2.reload
|
||||
assert_raises(ActiveRecord::ReadonlyAttributeError) do
|
||||
post_with_reload2.update(author: author2)
|
||||
end
|
||||
|
||||
post_without_reload = ReadonlyAuthorPost.create!(author: author1, title: "Hi", body: "there")
|
||||
post_without_reload.update(title: "Hello", body: "world")
|
||||
assert_equal author1, post_without_reload.author
|
||||
|
||||
post_without_reload2 = ReadonlyAuthorPost.create!(author: author1, title: "Hi", body: "there")
|
||||
assert_raises(ActiveRecord::ReadonlyAttributeError) do
|
||||
post_without_reload2.update(author: author2)
|
||||
end
|
||||
end
|
||||
|
||||
def test_unicode_column_name
|
||||
Weird.reset_column_information
|
||||
weird = Weird.create(なまえ: "たこ焼き仮面")
|
||||
|
|
Loading…
Reference in New Issue