如何在rails中处理这种类型的多级表单

我在轨道3.1。 我有以下型号

class Tool < ActiveRecord::Base has_many :comments end class Comment  :relationships, :source => :resource, :source_type => 'Advantage' has_many :disadvantages, :through => :relationships, :source => :resource, :source_type => 'Disadvantage' end class Relationship  true end class Disadvantage  :resource has_many :comments, :through => :relationships end class Advantage  :resource has_many :comments, :through => :relationships end 

简而言之,A Tool有很多commentsComment内容与AdvantagesDisadvantages相关联。 所以在我的tool/show页面中,我会列出所有评论。

但是如果我必须在工具页面上添加注释,那么会有一个表单有一个textarea用于注释和两个multi select list boxes的优缺点。

如果用户想要从现有的adv / disadv中选择,用户可以从列表框中选择,或者如果用户想要添加新的adv / disadv,他可以输入并添加它,这样就可以了。通过ajax调用保存,新的adv / disadv被添加到列表框中。 我该怎么做?

您正在寻找的是“嵌套表格” – 它们非常简单易用。

在你的Gemfile中添加:

 gem "nested_form" 

1)在你的main_model中 ,你将包含对accepts_nested_attributes_for :nested_model的调用accepts_nested_attributes_for :nested_model

 class MainModel accepts_nested_attributes_for :nested_model end 

2)在main_model而不是form_for() 的视图中 ,您将在顶部调用nested_form_for()

 = nested_form_for(@main_model) do |f| ... 

检查该方法的Rails页面,它有一些有趣的选项,例如:reject_if,:allow_destroy,…

3)在main_model的视图中 ,当你想显示嵌套模型的子表单时,你会做

 = f.fields_for :nested_model # replace with your other model name 

然后它将使用_form partial作为nested_model并将其嵌入到main_model的视图中

奇迹般有效!

查看这些RailsCast.com剧集,其中深入介绍了嵌套表格:

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

希望这可以帮助