Rails 4 允许散列中的任何键

Rails 4 permit any keys in the hash

我这样传递参数

{
  "utf8" => true,
  "supply" => {
    "items" => { 111 => 112, 89 => 10},
    "another_params" => "something"
  }
}

我的supply_params是:

params.fetch(:supply, {}).permit(:another_params, items: {})

但是我得到了 unpermitted parameters 111 and 89。如何让 items 允许所有类型的密钥?

根据@steve klein link to github issue,这被认为是一个很好的解决方案:

params.permit(:test).tap do |whitelisted|
  whitelisted[:more] = params[:more]
end

This thread中github提供了解决方案:

def supply_params
  params.require(:supply).permit(:another_params).tap do |whitelisted|
    whitelisted[:items] = params[:supply][:items] if params[:supply][:items]
  end
end

这个想法是明确允许需要的任何已知属性,然后添加嵌套属性。