Rails 4 permit any keys in the hash

时光怂恿深爱的人放手 提交于 2019-12-25 04:46:25

问题


I pass a params like this

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

My supply_params are:

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

But I get an unpermitted parameters 111 and 89. How can I make items permit all kinds of keys?


回答1:


This thread in github provides a solution:

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

The idea is to explicitly permit any known attributes which are needed and then tack on nested attributes.




回答2:


According to the @steve klein link to github issue, this is considered as a good solution:

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


来源:https://stackoverflow.com/questions/30894070/rails-4-permit-any-keys-in-the-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!