[英]Unpermitted Parameters with Hashes in Rails
I have a hash field in my Rails model and am attempting to update it. 我的Rails模型中有一个哈希字段,我正在尝试更新它。 The attribute, detail
, was first generated through a migration as a text
type. 属性detail
最初是通过迁移作为text
类型生成的。 Afterwords, in my model, it was set as a hash
through the store :detail
property 后来,在我的模型中,它通过store :detail
属性设置为hash
class Request < ActiveRecord::Base
store :detail
end
My strong_params are as such: 我的strong_params是这样的:
params.require(:request).permit(:name, :action, :detail => {})
However, when my Parameters go through as 但是,当我的参数通过时
Parameters: {"request"=>{"name"=>"temp", "action"=>"create", "detail"=>{"test"=>"fdsf"}}}
I am told that there is an Unpermitted parameter: test
, despite the test
parameter being part of the detail
hash. 我被告知有一个Unpermitted parameter: test
,尽管test
参数是detail
哈希的一部分。
How do I fix this? 我该如何解决? Thanks! 谢谢!
params.require(:request).permit(:name, :action, detail: [:test])
另一个选项(例如,如果您事先不知道可能的字段名称)将在客户端将detail
序列化为json字符串,接受它作为字符串并随后反序列化为哈希。
This (rather old) issue tackles your problem quite interestingly 这(而旧) 问题铲球你的问题很有趣
Considering your hash consists of more values than :test
you could try the solution with .tap
考虑到你的哈希包含的值多于:test
你可以尝试使用.tap
的解决方案
params.require(:request).permit(:name, :action).tap do |whitelisted|
whitelisted[:detail] = params[:request][:detail]
end
Or the somewhat less dynamic: 或者动态稍差:
params.require(:request).permit(:name, :action, :detail => [:test])
This blogpost sums up different approaches. 这篇博文总结了不同的方法。
edit 编辑
You need your detail
column to be of type 'text' to be able to save the hash as a string. 您需要将detail
列设置为“text”类型才能将散列保存为字符串。 In your Request
model add this to the top: 在您的Request
模型中,将其添加到顶部:
serialize :detail
as it will allow to interpret the stringified :detail
as a hash 因为它将允许将字符串化的:detail
解释为散列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.