【问题标题】:Strong params for nested model attributes in a form in a Rails 4 applicationRails 4 应用程序中表单中嵌套模型属性的强参数
【发布时间】:2018-04-02 18:04:54
【问题描述】:

我在连接到 Postgres 数据库的 Rails 4 应用程序中使用 Cocoon gem(https://github.com/nathanvda/cocoon) 来构建嵌套模型表单。我在我的项目控制器中允许嵌套模型(所有者)的属性如下

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

所有者表中的杂项列是 json 类型。我无法在上面所需的参数中正确指定杂项。假设 miscellanous 可以有以下键: favorite_color 和 favorite_movie。如何在上面的强参数中指定?

如果我执行以下操作:

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

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

如何使用强参数正确地允许嵌套模型所有者使用名为 miscellanous 的 json 列?

【问题讨论】:

  • 你在哪一行得到错误,因为强参数声明乍一看似乎完全没问题。 json属性怎么定义的,可能哪里有问题?

标签: ruby-on-rails ruby-on-rails-4 strong-parameters cocoon-gem


【解决方案1】:

一些事情:

  1. 您可以允许带有空哈希括号的未知键的哈希。
  2. 不要忘记您需要所有者的 ID。
  3. 请注意杂项中缺少的“e”。

试试这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多