Rah*_*hul 2 ruby-on-rails ruby-on-rails-3.1
我在轨道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
Run Code Online (Sandbox Code Playgroud)
简而言之,A Tool有很多comments.转换Comment与Advantages和相关联Disadvantages.所以在我的tool/show页面中,我会列出所有评论.
但是如果我必须在工具页面上添加注释,那么会有一个表单有一个textarea用于注释,两个multi select list boxes表示优点和缺点.
如果用户想要从现有的adv/disadv中选择,用户可以从列表框中选择,或者如果用户想要添加新的adv/disadv,他可以输入并添加它,这样就可以了.通过ajax调用保存,新的adv/disadv被添加到列表框中.我该怎么做?
您正在寻找的是"嵌套表格" - 它们非常简单易用.
在您的Gemfile中添加:
gem "nested_form"
Run Code Online (Sandbox Code Playgroud)
1)在你的main_model中,你将包含一个调用accepts_nested_attributes_for :nested_model
class MainModel
accepts_nested_attributes_for :nested_model
end
Run Code Online (Sandbox Code Playgroud)
2)在main_model而不是form_for()的视图中,您将在顶部调用nested_form_for()
= nested_form_for(@main_model) do |f|
...
Run Code Online (Sandbox Code Playgroud)
检查该方法的Rails页面,它有一些有趣的选项,例如:reject_if,:allow_destroy,...
3)在main_model的视图中,当你想显示嵌套模型的子表单时,你会做
= f.fields_for :nested_model # replace with your other model name
Run Code Online (Sandbox Code Playgroud)
然后它将使用_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
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |