diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index e3ed3780dbdfe21e9c45e517f13e4a6df6b54161..1a34ed441f261f3ec868e413d23f447672976def 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,10 @@ ## Rails 4.0.0 (unreleased) ## +* Prevent mass assignment to the type column of polymorphic associations when using `build` + Fix #8265 + + *Yves Senn* + * Deprecate calling `Relation#sum` with a block. To perform a calculation over the array result of the relation, use `to_a.sum(&block)`. diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb index 99e7383d42f2a3bf1cf7df77624bc01445c7cdcd..3f0e4ca99979eefb9c5cd0d90e22f3a9a72917bb 100644 --- a/activerecord/lib/active_record/associations/association.rb +++ b/activerecord/lib/active_record/associations/association.rb @@ -232,7 +232,8 @@ def stale_state def build_record(attributes) reflection.build_association(attributes) do |record| - attributes = create_scope.except(*(record.changed - [reflection.foreign_key])) + skip_assign = [reflection.foreign_key, reflection.type].compact + attributes = create_scope.except(*(record.changed - skip_assign)) record.assign_attributes(attributes) end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 6cdc16653397488ceaf83b8214fec712266c9160..2ded97582dc98b58fdbde6a8ff7f8ce9a9256da1 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1579,6 +1579,14 @@ def test_abstract_class_with_polymorphic_has_many assert_equal [tagging], post.taggings end + def test_build_with_polymotphic_has_many_does_not_allow_to_override_type_and_id + welcome = posts(:welcome) + tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => 'ShouldNotChange') + + assert_equal welcome.id, tagging.taggable_id + assert_equal 'Post', tagging.taggable_type + end + def test_dont_call_save_callbacks_twice_on_has_many firm = companies(:first_firm) contract = firm.contracts.create!