Rails 4 允许哈希中的任何键 [英] Rails 4 permit any keys in the hash

查看:53
本文介绍了Rails 4 允许哈希中的任何键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递这样的参数

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

我的 supply_params 是:

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

但是我得到一个不允许的参数 111 和 89.如何让 items 允许所有类型的密钥?

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

推荐答案

此主题在github中提供了解决方案:

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.

这篇关于Rails 4 允许哈希中的任何键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆