关于 ruby??:Rails 4 Unpermitted Parameters for Array | 珊瑚贝

Rails 4 Unpermitted Parameters for Array


我的模型中有一个数组字段,我正在尝试更新它。

我的强参数方法如下

1
2
3
4
5
def post_params
  params[“post”][“categories”] = params[“post”][“categories”].split(“,”)

  params.require(:post).permit(:name, :email, :categories)
end

我在控制器中的操作如下

1
2
3
4
5
6
7
8
9
def update
  post = Post.find(params[:id]

  if post and post.update_attributes(post_params)
    redirect_to root_url
  else
    redirect_to posts_url
  end
end

但是,每当我提交更新帖子时,我都会在我的开发日志中看到

1
Unpermitted parameters: categories

传递的参数是

1
2
3
  Parameters: {“utf8”=>“?”,“authenticity_token”=>“auth token”,“id”=>“10”,

“post”=>{“name”=>“Toni Mitchell”,“email”=>“eileen_hansen@hayetokes.info”,“categories”=>“,2”}}

我想这与属性 categories 是一个数组这一事实有关,因为其他一切看起来都很好。再说一次,我可能是错的。那么,我的代码有什么问题,为什么在明确允许的情况下不让我保存类别字段?谢谢。

  • 这可能是由于您设置类别参数值的方式,iirc params 对象不是简单的哈希,您是否尝试过更简单的示例?


试试这个

1
params.require(:post).permit(:name, :email, :categories => [])

(忽略我的评论,我认为这不重要)

  • 嗨,我有一个问题出价(#69846105528920)预期,得到字符串(#8248680)
  • 您好,有没有办法根据数组中的类别查找帖子,例如 Post.find_by(tags: ‘sports’) ?
  • 也很高兴解释为什么这有效@slicedpan


在 rails 4 中,即

1
params.require(:post).permit(:name, :email, {:categories => []})
  • 这对我有用,但是如果我们已经在模型中定义了该属性的序列化,为什么还需要在单独的哈希中呢?


允许的标量类型为 String、Symbol、NilClass、Numeric、TrueClass、FalseClass、Date、Time、DateTime、StringIO、、ActionDispatch::Http::UploadedFile 和 Rack::Test::UploadedFile.

要声明 params 中的值必须是允许的标量值数组,请将键映射到空数组:

1
params.permit(:id => [])

Github 上的强参数文档是这样说的:

1
params.require(:post).permit(:name, :email, :categories => [])

我希望这对你有用。


我遇到了同样的问题,但是仅仅添加数组来允许是不够的。我也必须添加类型。这样:

1
params.require(:transaction).permit(:name, :tag_ids => [:id])

我不确定这是否是完美的解决方案,但在那之后,\\’Unpermitted parameters\\’日志消失了。


我从这篇出色的帖子中找到了该解决方案的提示:http://patshaughnessy.net/2014/6/16/a-rule-of-thumb-for-strong-parameters


我遇到了同样的问题,但在我的情况下,我还必须更改:

<input type=”checkbox” name=”photographer[attending]” value=”Baku”>

到:

<input type=”checkbox” name=”photographer[attending][]” value=”Baku”>

希望这对某人有所帮助。


如果有多个item和item_array这样的参数里面-

1
2
Parameters {“item_1”=>“value 1”,“item_2”=> {“key_1”=>“value A1”,
“key_2”=>[“val B2”,“val C3”]} }

我们在 item_2 中有数组。
可以允许如下-

1
params.permit(item_2: [:key_1, :key_2 => [] ])

上面拯救了我的一天,可能对你也有帮助。


来源:https://www.codenong.com/17868746/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9515.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?