Rails 3 Nested Model Form, 2 levels deep using accepts_nested_attributes_for

后端 未结 1 522
清歌不尽
清歌不尽 2020-12-29 11:28

My nested model form is working great on the first level deep. But I was under the impression that you could go many levels deep using accepts_nested_attributes_for. But w

相关标签:
1条回答
  • 2020-12-29 11:45

    I think you've got the form variables slightly mixed up. It should be:

    = form_for @question, :html => {:multipart => true} do |f|
    
      = f.label :text, "Question Text:"
      = f.text_area :text, :rows => 7
    
      %br
      %br
    
      =f.fields_for :answer, do |af|
        = af.label :body, "Answer Text:"
        = af.text_area :body, :rows => 7
    
        %br
        %br
    
        = af.fields_for :image do |img_form|
          = img_form.label :title, "Image Title:"
          = img_form.text_field :title
    
          %br
    
          = img_form.label :file, "Image File:"
          = img_form.file_field :file
    
          %br
    
          = img_form.label :caption, "Image Caption:"
          = img_form.text_area :caption, :rows => 7
    
      = hidden_field_tag("case_id", value = @case_id)
    
      = f.submit
    

    Notice how form_for ... do |f| spawns f.fields_for ... do |af|, which in turns spawns af.fields_for ... do |img_form|.

    The key is the second fields_for. It should be af.fields_for :image do |img_form| rather than f.fields_for :image do |img_form|.

    0 讨论(0)
提交回复
热议问题