我有4个模型报告,类别,问题,答案。我的问题是报告与类别没有关联。我想创建嵌套表单,如:
@report= Report.new
@category = @report.build_category
@quetions = @category.questions.build
@questions.answers.build
但如果没有关联类别的报告,我就无法做到。我有像 categories.report_id不存在的错误我做错了什么?
我的协会:
类别=>有很多=>问题
问题=>有很多=>答案
我的数据库架构
Reports:
user_id: integer
category_id:integer
Category:
title: string
slug: string
Question:
title: string
category_id: integer
Answer:
title: string
question_id: integer
答案 0 :(得分:1)
我建议使用NestedForm Gem(https://github.com/ryanb/nested_form)
gem 'nested_form'
您需要在控制器中执行以下操作:
@report= Report.new
@report.build_category
然后在视图中:
<%= nested_form_for @report do |f| %>
<%= f.fields_for :category do |category_form| %>
<%= category_form.text_field :name %>
<%= category_form.fields_for :questions do |question_form| %>
<%= question_form.text_field :question %>
<%= question_form.fields_for :answers do |answer_form| %>
<%= answer_form.text_field :answer %>
<% end %>
<p><%= question_form.link_to_add "Add a Answer", :answers %></p>
<% end %>
<p><%= category_form.link_to_add "Add a Question", :questions %></p>
<% end %>