Rails - 强参数 - 嵌套对象 [英] Rails - Strong Parameters - Nested Objects

查看:25
本文介绍了Rails - 强参数 - 嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题.但目前还没有找到解决方案.

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]})


Rails 实际上有很好的文档说明: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

为进一步说明,您可以查看permitstrong_parameters 本身的实现:https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247

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 - 强参数 - 嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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