Skip to content

Commit 053bfa2

Browse files
author
Yves Senn
committed
prevent mass assignment of polymorphic type when using build
Closes rails#8265
1 parent 293c121 commit 053bfa2

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
## Rails 4.0.0 (unreleased) ##
22

3+
* Prevent mass assignment to the type column of polymorphic associations when using `build`
4+
Fix #8265
5+
6+
*Yves Senn*
7+
38
* Fix postgresql adapter to handle BC timestamps correctly
49

510
HistoryEvent.create!(:name => "something", :occured_at => Date.new(0) - 5.years)

activerecord/lib/active_record/associations/association.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,8 @@ def stale_state
232232

233233
def build_record(attributes)
234234
reflection.build_association(attributes) do |record|
235-
attributes = create_scope.except(*(record.changed - [reflection.foreign_key]))
235+
skip_assign = [reflection.foreign_key, reflection.type].compact
236+
attributes = create_scope.except(*(record.changed - skip_assign))
236237
record.assign_attributes(attributes)
237238
end
238239
end

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,6 +1579,14 @@ def test_abstract_class_with_polymorphic_has_many
15791579
assert_equal [tagging], post.taggings
15801580
end
15811581

1582+
def test_build_with_polymotphic_has_many_does_not_allow_to_override_type_and_id
1583+
welcome = posts(:welcome)
1584+
tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => 'ShouldNotChange')
1585+
1586+
assert_equal welcome.id, tagging.taggable_id
1587+
assert_equal 'Post', tagging.taggable_type
1588+
end
1589+
15821590
def test_dont_call_save_callbacks_twice_on_has_many
15831591
firm = companies(:first_firm)
15841592
contract = firm.contracts.create!

0 commit comments

Comments
 (0)