2011-10-06 60 views
2

我在rails 3.1中。我有以下型号我该如何在rails中处理这种类型的多级表单

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有许多comments。 A Comment inturn与AdvantagesDisadvantages相关联。因此,在我的tool/show页面中,我将列出所有评论。

但是,如果我必须添加注释到工具页面,将会有一个表单,其中有一个textarea的评论和两个multi select list boxes的优点和缺点。

这里有一个问题,如果用户想从现有的adv/disadvantagev中选择,用户可以从列表框中选择,或者如果用户想要添加一个新的副/他可以键入并添加它,以便通过ajax调用保存并将新的副/副列表添加到列表框中。我该如何做到这一点?

回答

5

您要找的是什么“嵌套表格” - 它们非常简单易用。

在你的Gemfile添加:在您的MAIN_MODEL

gem "nested_form" 

1),你会包括在视图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部分作为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

希望这有助于

+1

我要提及nested_form是宝石 – maxenglander

+0

好点!谢谢! – Tilo

相关问题