Skip to content

Commit 68af636

Browse files
committed
Ensure that ActionController::Parameters can still be passed to AR
Since nested hashes are also instances of `ActionController::Parameters`, and we're explicitly looking to work with a hash for nested attributes, this caused breakage in several points. This is the minimum viable fix for the issue (and one that I'm not terribly fond of). I can't think of a better place to handle this at the moment. I'd prefer to use some sort of solution that doesn't special case AC::Parameters, but we can't use something like `to_h` or `to_a` since `Enumerable` adds both. While I've added a trivial test case for verifying this fix in isolation, we really need better integration coverage to prevent regressions like this in the future. We don't actually have a lot of great places for integration coverage at the moment, so I'm deferring it for now. Fixes rails#20922.
1 parent c7449a2 commit 68af636

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

activerecord/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
* Ensure that `ActionController::Parameters` can still be passed to nested
2+
attributes.
3+
4+
Fixes #20922.
5+
6+
*Sean Griffin*
7+
18
* Deprecate force association reload by passing a truthy argument to
29
association method.
310

activerecord/lib/active_record/nested_attributes.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,9 @@ def _destroy
386386
# then the existing record will be marked for destruction.
387387
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
388388
options = self.nested_attributes_options[association_name]
389+
if attributes.respond_to?(:permitted?)
390+
attributes = attributes.to_h
391+
end
389392
attributes = attributes.with_indifferent_access
390393
existing_record = send(association_name)
391394

activerecord/test/cases/nested_attributes_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,4 +1064,27 @@ def setup
10641064
assert_not part.valid?
10651065
assert_equal ["Ship name can't be blank"], part.errors.full_messages
10661066
end
1067+
1068+
class ProtectedParameters
1069+
def initialize(hash)
1070+
@hash = hash
1071+
end
1072+
1073+
def permitted?
1074+
true
1075+
end
1076+
1077+
def to_h
1078+
@hash
1079+
end
1080+
end
1081+
1082+
test "strong params style objects can be assigned" do
1083+
params = { name: "Stern", ship_attributes:
1084+
ProtectedParameters.new(name: "The Black Rock") }
1085+
part = ShipPart.new(params)
1086+
1087+
assert_equal "Stern", part.name
1088+
assert_equal "The Black Rock", part.ship.name
1089+
end
10671090
end

0 commit comments

Comments
 (0)