【问题标题】:Working with has_many through:, accepts_nested_attributes_for, and fields_for通过:、accepts_nested_attributes_for 和 fields_for 使用 has_many
【发布时间】:2012-01-06 10:18:12
【问题描述】:

好的,所以我有 4 个模型用户、项目、文件和项目文件

class User < ActiveRecord::Base
  has_many :files
end

class Project < ActiveRecord::Base
  has_many :projects_files
  has_many :files, through: :projects_files
end

class File < ActiveRecord::Base
  has_many :projects_files
  has_many :projects, through: :projects_files
end

class ProjectsFiles < ActiveRecord::Base
  belongs_to :project
  belongs_to :file
end

创建项目时,我希望我的表单显示带有复选框的用户文件列表。用户将能够检查他们想要添加到项目中的文件,该项目应该为每个检查的文件构建一个 ProjectsFile 并销毁任何未检查的 ProjectsFile。 Accepts_nested_attributes_for 和 fields_for 可以做到这一点吗?我一直在尝试几种不同的东西,但我无法做到正确。有什么好的方法来解决这个问题?有没有更好的办法?

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

是的,您可以使用accepts_nested_attributes_for 和fields_for,请查看此demo。这是演示的source code

希望对您有所帮助。

【讨论】:

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