2010-10-06 4 views
5

3 가지 모델이 다중 모델 형식으로 제공됩니다.레일즈 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는 $(new_child_form).clone().insertBefore($(new_child_form))과 같은 일부 jquery를 트리거하는 생성 버튼을 가지고있어 하나 이상의 자식 모델이 동일한 양식 제출에 추가 될 수 있습니다. 저는 아약스를 통해 각 어린이 양식을 개별적으로 제출할 수 있지만 이것이 내가 원하는 것은 아니라는 것을 알고 있습니다.

레일이 하나 이상 parent[children_attributes][0][other_children_attributes][1]을 얻고 있으며 마지막 하나만 사용하는 것 같습니다. 어떤 아이디어?

답변

5

복제하려면 jQuery를 사용하거나 사용하지 않고이 작업을 수행 할 수 있습니다. 필자는 요소를 삽입했지만 현재 시간을 기반으로 고유 한 ID를 생성하는 자바 스크립트를 호출하도록 링크를 설정함으로써이 문제를 해결했습니다. 복제를 위해 jQuery를 사용한다면 복제 된 필드의 ID를 업데이트해야만 Rails에서 새로운 자식으로 처리 할 수 ​​있습니다. Ryan BatesRailscasts 196-197에서이를 수행하는 방법을 설명하고 그의 솔루션은 Rails 3에서 계속 작동합니다.