简体   繁体   English

Rails 4应用程序中表单中嵌套模型属性的强大参数

[英]Strong params for nested model attributes in a form in a Rails 4 application

Im using Cocoon gem( https://github.com/nathanvda/cocoon ) in my Rails 4 application connected to a Postgres database for building a nested model form. 我在连接到Postgres数据库的Rails 4应用程序中使用Cocoon gem( https://github.com/nathanvda/cocoon )来构建嵌套模型表单。 I have permitted the attributes of the nested model (owner) in my projects controller as follows 我已在我的项目控制器中允许嵌套模型(所有者)的属性,如下所示

params.
        require(:project).
        permit(:name, :description,
               owners_attributes: [:name, :email, :miscellanous, :_destroy])

miscellanous column in owners table is of type json . 所有者表中的其他列的类型为json。 Im unable to specify miscellanous correctly in the required params above. 我无法在上面要求的参数中正确指定杂项。 Suppose miscellanous can have the following keys: favorite_color and favorite_movie. 假设其他项可以具有以下键:favorite_color和收藏夹_电影。 How can i specify that in the strong params above ? 我如何在上面的强参数中指定它?

If i do the following: 如果我执行以下操作:

params.
    require(:project).
    permit(:name, :description,
           owners_attributes: [:id, :_destroy, :name, :email, miscellanous_attributes: [:favorite_color, :favorite_movie] ])

I get syntax error, unexpected ']', expecting => 我收到syntax error, unexpected ']', expecting =>

How can i correctly permit the json column called miscellanous for the nested model owners using strong params ? 我如何正确地允许使用强参数的嵌套模型所有者使用名为杂项的json列?

A few things: 一些东西:

  1. You can permit a hash with unknown keys with an empty hash bracket. 您可以允许带有未知密钥的哈希使用空的哈希括号。
  2. Don't forget you need the ID for your owners. 不要忘记您需要所有者的ID。
  3. Note the missing 'e' in miscellaneous. 注意其他杂项中缺少的“ e”。

Try something like this: 尝试这样的事情:

params.
    require(:project).
    permit(:name, :description,
           owners_attributes: [:id, :name, :email, miscellaneous: {}, :_destroy])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM