2010-10-06 70 views
5

我有三個模型以多模型形式呈現。Rails 3多模型窗體與多個新的子模型實例

class Parent < ActiveRecord::Base 
    has_many :children 
    accepts_nested_attributes_for :children 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent 
    has_many :other_children 
    accepts_nested_attributes_for :other_children 
end 

class OtherChild < ActiveRecord::Base 
    belongs_to :child 
end 

= form_for @parent do |f| 
    # fields for parent 
    = f.fields_for :children, @parent.children do |cf| 
    = cf.fields_for :other_children, @parent.children do |ocf| 
     # fields_for other child 
    = cf.fields_for :other_children, @parent.children.new do |ocf| 
     # fields_for other child 

這有效,除非我通過jquery複製第二組子域。更清楚的是,新的other_child模型的fields_for有一個創建按鈕,它觸發了一些jQuery,如$(new_child_form).clone().insertBefore($(new_child_form))允許在同一個表單中添加多個子模型。我知道我可以通過ajax單獨提交每個子表單,但這不是我想要的。

Rails越來越多parent[children_attributes][0][other_children_attributes][1],似乎只使用最後一個。有任何想法嗎?

回答

5

您可以使用或不使用jQuery進行克隆。我通過鏈接調用JavaScript來解決這個問題,該插入元素插入了元素,但基於當前時間生成了唯一ID。如果你確實使用jQuery進行克隆,你必須確保更新克隆字段的ID,以便Rails將它們視爲新的子項。 Ryan Bates說明如何在Railscasts 196-197中執行此操作,並且他的解決方案可以繼續使用Rails 3.