How can I achieve something like this?
The structure is => a test has many questions, and a question has many answers.
我怎样才能实现这样的目标?结构是=>测试有很多问题,一个问题有很多答案。
I have questions = @test.questions.build
and questions.answers.build
in the controller.
我在控制器中有问题= @ test.questions.build和questions.answers.build。
form_for @test do |f|
f.fields_for :questions do |question_f|
question_f.fields_for :answers do |answer_f|
# answer form here
It works untill the fields_for :answers.
它的工作原理直到fields_for:answers。
What am I missing? Thanks!
我错过了什么?谢谢!
1 个解决方案
#1
3
You should also put accepts_nested_attributes_for
in your Test and Question model if you want use nested form:
如果要使用嵌套形式,还应在您的测试和问题模型中放置accepts_nested_attributes_for:
class Test < ActiveRecord::Base
attr_accessible :questions_attributes
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
attr_accessible :answers_attributes
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers
end
Try this:
form_for ([@test, @question]) do |f|
and in your new action in controller:
并在控制器中的新操作中:
@test = Test.new
@question = Question.new
@test.questions.build
@question.answers.build
#1
3
You should also put accepts_nested_attributes_for
in your Test and Question model if you want use nested form:
如果要使用嵌套形式,还应在您的测试和问题模型中放置accepts_nested_attributes_for:
class Test < ActiveRecord::Base
attr_accessible :questions_attributes
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
attr_accessible :answers_attributes
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers
end
Try this:
form_for ([@test, @question]) do |f|
and in your new action in controller:
并在控制器中的新操作中:
@test = Test.new
@question = Question.new
@test.questions.build
@question.answers.build