使用 simple_form 和 rails 4 创建多个嵌套表单 [英] Creating multiple nested forms using simple_form and rails 4
问题描述
我正在尝试使用以下模型创建一个简单的应用程序:类别--[has_many]--> 问题--[has_many]--> 答案
I'm trying to create a simple app with the following models: categories --[has_many]--> questions --[has_many]--> answers
我有以下代码来创建类别+问题(类别/_form.haml.html):
I have the following code for creating categories + questions(categories/_form.haml.html):
= simple_form_for(@category) do |f|
= f.error_notification
= f.input :title, label: "Category title: "
= f.simple_fields_for :questions, @category.questions.build do |q|
= q.input :content, label: "Question content: "
= f.button :submit
而且我使用所有相同的代码来创建问题 + 答案(questions/_form.haml.html).我已经配置了所有关系、强参数、嵌套属性和控制器,它对我来说很好用.
And I'm using all the same code for creating questions + answers(questions/_form.haml.html). I have all the relations, strong parameters, nested attrs and controllers configured, it works just fine for me.
两个问题:
如何在类别/_form.haml.html 中创建多个问题?
How to create multiple questions in categories/_form.haml.html?
如何同时创建类别+多个问题+每个问题的多个答案(在类别/_form.haml.html中)?
How to create category + multiple questions + multiple answers per each question at once(in categories/_form.haml.html)?
我花了几个小时试图弄清楚如何完成第二个,我能找到的所有信息都与 Rails 3.0 和 form_for 相关.他们都没有为我工作.
I've spent a few hours trying to figure out how to accomplish the second one and all the info I was able to find is related to Rails 3.0 and form_for. None of them worked for me.
这里最直接的解决方案应该是:
The most straightforward solution here should be something like:
= simple_form_for(@category) do |f|
= f.error_notification
= f.input :title, label: "Category title: "
= f.simple_fields_for :questions, @category.questions.build do |q|
= q.input :content, label: "Question content: "
= q.simple_fields_for :answers, q.questions.build do |a|
= a.input :content, label: "Answer content"
= f.button :submit
但它给了我
undefined method `questions' for #<SimpleForm::FormBuilder:
我在这里遗漏了什么?
推荐答案
你弄错了:= q.simple_fields_for :answers, q.questions.build do |a|
您在构建器对象 q
而不是模型对象上调用 questions
方法.可能你想要这个:
You got it wrong here: = q.simple_fields_for :answers, q.questions.build do |a|
You are calling questions
method on builder object q
instead of a model object.
Probably You want this:
= q.simple_fields_for :answers, q.object.questions.build
这篇关于使用 simple_form 和 rails 4 创建多个嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!