【问题标题】:Can't create associated models on update action无法在更新操作上创建关联模型
【发布时间】:2019-03-20 20:01:38
【问题描述】:

我在为 has_many through 关系创建关联模型时遇到困难:

我有 3 个模型:Project、Material、ProjectMaterial

请记住,材料数据库表预先填充了 1000 多种材料,当创建新的项目时,用户可以选择他们想要用于特定建筑项目的材料

我有以下架构:

Project < ApplicationRecord
 has_many :project_materials 
 has_many :materials, through: project_materials

Material < ApplicationRecord
 belongs_to :category

ProjectMaterial < ApplicationRecord
 belongs_to :project
 belongs_to :material

在 Project#Show 页面中,我有一个当前项目的表单,在这个表单中,我渲染 Material 表中的所有材质,以便为当前项目选择(从参数哈希中获取)。

*更新后,我希望能够将所有选定的材料自动保存到 ProjectMaterial 表中

这是表格: Project update form

表单内的材质分为类别,并通过一个类别集部分渲染(显示特定类别的材料)Category partial

这是实际应用的照片:Form/Partial view

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-4 model-view-controller


    【解决方案1】:

    我相信您必须使用嵌套属性,在模型中使用 accepts_nested_attributes_for,然后在表单上,​​使用 f.fields_for 为关联模型创建表单。

    https://thoughtbot.com/blog/accepts-nested-attributes-for-with-has-many-through

    【讨论】:

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