简体   繁体   中英

Permit hash or nil with strong parameters

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM