问题描述
我有一个非常简单的问题.但是到目前为止,还没有找到解决方案.
I've got a pretty simple question. But haven't found a solution so far.
这是我发送到服务器的JSON字符串:
So here's the JSON string I send to the server:
{
"name" : "abc",
"groundtruth" : {
"type" : "Point",
"coordinates" : [ 2.4, 6 ]
}
}
使用新的许可方法,我得到了:
Using the new permit method, I've got:
params.require(:measurement).permit(:name, :groundtruth)
这不会引发任何错误,但是创建的数据库条目包含null
而不是groundtruth值.
This throws no errors, but the created database entry contains null
instead of the groundtruth value.
如果我刚设置:
params.require(:measurement).permit!
一切都按预期方式保存,但这当然会破坏强大参数所提供的安全性.
Everything get's saved as expected, but of course, this kills the security provided by strong parameters.
我找到了解决方案,如何允许使用数组,但没有一个使用嵌套对象的示例.这一定是有可能的,因为它应该是一个非常普通的用例.那么,它是如何工作的?
I've found solutions, how to permit arrays, but not a single example using nested objects. This must be possible somehow, since it should be a pretty common use case. So, how does it work?
推荐答案
当您想允许嵌套属性时,您确实会在数组中指定嵌套对象的属性,这听起来很奇怪.在您的情况下,将是
As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be
更新,由@RafaelOliveira建议
Update as suggested by @RafaelOliveira
params.require(:measurement)
.permit(:name, :groundtruth => [:type, :coordinates => []])
另一方面,如果您想嵌套多个对象,则可以将其包装在散列中……就像这样
On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this
params.require(:foo).permit(:bar, {:baz => [:x, :y]})
铁路实际上对此有很好的文档: http://api.rubyonrails. org/classes/ActionController/Parameters.html#method-i-permit
Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit
为进一步说明,您可以查看permit
和strong_parameters
本身的实现:
For further clarification, you could look at the implementation of permit
and strong_parameters
itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247
这篇关于Rails 4-强参数-嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!