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

时间:2011-10-06 07:39:31

标签: ruby-on-rails ruby-on-rails-3.1

我在rails 3.1中。我有以下型号

    class Tool < ActiveRecord::Base
        has_many :comments
    end

    class Comment < ActiveRecord::Base
        belongs_to :tool
        has_many :relationships
        has_many :advantages, :through => :relationships, :source => :resource, :source_type => 'Advantage'
        has_many :disadvantages, :through => :relationships, :source => :resource, :source_type => 'Disadvantage'

    end

    class Relationship < ActiveRecord::Base
        belongs_to :comment
        belongs_to :resource, :polymorphic => true
    end

    class Disadvantage < ActiveRecord::Base
        has_many :relationships, :as => :resource
        has_many :comments, :through => :relationships
    end

    class Advantage < ActiveRecord::Base
        has_many :relationships, :as => :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被添加到列表框中。我该怎么做?

1 个答案:

答案 0 :(得分:5)

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

在您的Gemfile中添加:

gem "nested_form"

1)在您的main_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

希望这会有所帮助