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.
The best thing to do here, I think, is to allow all values by doing this:
This should allow anything through, even nil but then check the type by writing your own custom validation.
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.