0
votes

I'm trying to permit either a hash with certain values or a nil value through strong parameters. I now have the following:

params.require(:parent).permit(child: [:attr1, :attr2])

If I call this action with:

{ "parent": { "child": nil }}

Rails does not permit the child parameter. (Unpermitted parameter: child)

How do I convince rails that both nil and a hash is permitted? I know you can allow nil values by doing:

params.require(:parent).permit(:child, child: [:attr1, :attr2])

But this also allows string values.

1
are you trying to allow a hash input, or accept nested resources? those are very different use casesTheRealMrCrowley

1 Answers

2
votes

The best thing to do here, I think, is to allow all values by doing this:

params.require(:parent).permit(:child)

This should allow anything through, even nil but then check the type by writing your own custom validation.

validate :child_is_nil_or_hash
...
def child_is_nil_or_hash
  unless child.is_a?(Hash) || child.nil?
    errors.add(:child, 'must be nil or a hash')
  end
end

or something to that effect. I haven't tested this code properly.

In this example, you're moving the responsibility for validation away from the parameter whitelist and in to Rails validations where it belongs.