Skip to content

Commit b5d4dd4

Browse files
committed
Ensure that 'ActionController::Parameters' can still be passed to AR for collection associations
1 parent 2a0a264 commit b5d4dd4

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

activerecord/lib/active_record/nested_attributes.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,9 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
445445
# ])
446446
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
447447
options = self.nested_attributes_options[association_name]
448+
if attributes_collection.respond_to?(:permitted?)
449+
attributes_collection = attributes_collection.to_h
450+
end
448451

449452
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
450453
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
@@ -471,6 +474,9 @@ def assign_nested_attributes_for_collection_association(association_name, attrib
471474
end
472475

473476
attributes_collection.each do |attributes|
477+
if attributes.respond_to?(:permitted?)
478+
attributes = attributes.to_h
479+
end
474480
attributes = attributes.with_indifferent_access
475481

476482
if attributes['id'].blank?

activerecord/test/cases/nested_attributes_test.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1074,17 +1074,29 @@ def permitted?
10741074
true
10751075
end
10761076

1077+
def [](key)
1078+
@hash[key]
1079+
end
1080+
10771081
def to_h
10781082
@hash
10791083
end
10801084
end
10811085

1082-
test "strong params style objects can be assigned" do
1086+
test "strong params style objects can be assigned for singular associations" do
10831087
params = { name: "Stern", ship_attributes:
10841088
ProtectedParameters.new(name: "The Black Rock") }
10851089
part = ShipPart.new(params)
10861090

10871091
assert_equal "Stern", part.name
10881092
assert_equal "The Black Rock", part.ship.name
10891093
end
1094+
1095+
test "strong params style objects can be assigned for collection associations" do
1096+
params = { trinkets_attributes: ProtectedParameters.new("0" => ProtectedParameters.new(name: "Necklace"), "1" => ProtectedParameters.new(name: "Spoon")) }
1097+
part = ShipPart.new(params)
1098+
1099+
assert_equal "Necklace", part.trinkets[0].name
1100+
assert_equal "Spoon", part.trinkets[1].name
1101+
end
10901102
end

0 commit comments

Comments
 (0)