使用has_many through:,accepts_nested_attributes_for和fields_for

时间:2012-01-06 01:45:37

标签: ruby-on-rails

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

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。 Accept_nested_attributes_for和fields_for可以实现吗?我一直在尝试几种不同的东西,但我无法做到。有什么好办法可以解决这个问题?还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

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

希望这可以帮到你。