我正在试图为一个模型制作一个表单,它具有动态数量的嵌套模型.我使用嵌套表单(如
RailsCasts 197所述).为了使事情变得更复杂,我的每个嵌套模型都有一个与第三个模型的has_one关联,我也希望将其添加到表单中.
对于任何想要超标准化或不正当的方法的人来说,这个例子是我面临的问题的简化版本.事实上,事情稍微复杂一些,这是我们决定采取的方法.
一些示例代码来说明下面的问题:
- #MODELS
- class Test
- attr_accessible :test_name,:test_description,:questions_attributes
- has_many :questions
- accepts_nested_attributes_for :questions
- end
- class Question
- attr_accessible :question,:answer_attributes
- belongs_to :test
- has_one :answer
- accepts_nested_attributes_for :answer
- end
- class Answer
- attr_accessible :answer
- belongs_to :question
- end
- #CONTROLLER
- class TestsController < ApplicationController
- #GET /tests/new
- def new
- @test = Test.new
- @questions = @test.questions.build
- @answers = @questions.build_answer
- end
- end
- #VIEW
- <%= form_for @test do |f| %>
- <%= f.label :test_name %>
- <%= f.text_Box :test_name %>
- <%= f.label :test_description %>
- <%= f.text_area :test_description %>
- <%= f.fields_for :questions do |questions_builder| %>
- <%= questions_builder.label :question %>
- <%= questions_builder.text_Box :question %>
- <%= questions_builder.fields_for :answer do |answers_builder| %>
- <%= answers_builder.label :answer %>
- <%= answers_builder.text_Box :answer %>
- <% end %>
- <% end %>
- <%= link_to_add_fields 'New',f,:questions %>
- <% end %>
这个代码示例完全适用于Question的第一个实例.当另一个问题被动态添加以创建时,会发生此问题;答案字段不显示.我相信这是因为它们只是为了控制器中的第一个问题而建立的.有没有办法实现这个使用nested_attributes?
解决方法
我在这里解决了自己的问题.我所做的是,而不是在控制器中构建答案模型(这是不可能的,当你不知道在视图中会出现多少问题)时,我在调用fields_for时构建它:
- #CONTROLLER
- class TestsController < ApplicationController
- #GET /tests/new
- def new
- @test = Test.new
- @questions = @test.questions.build
- end
- end
- #VIEW
- <%= form_for @test do |f| %>
- <%= f.label :test_name %>
- <%= f.text_Box :test_name %>
- <%= f.label :test_description %>
- <%= f.text_area :test_description %>
- <%= f.fields_for :questions do |questions_builder| %>
- <%= questions_builder.label :question %>
- <%= questions_builder.text_Box :question %>
- <%= questions_builder.fields_for :answer,@questions.build_answer do |answers_builder| %>
- <%= answers_builder.label :answer %>
- <%= answers_builder.text_Box :answer %>
- <% end %>
- <% end %>
- <%= link_to_add_fields 'New',:questions %>
- <% end %>
这样做是因为无论正在建立多少个问题形式,构建了一个针对正在建立的问题的新答案.