Reputation: 69
I have 4 models Reports, Category, Question, Answer. My problem is that Report doesn't have associations with category. I want to create nested form like:
@report= Report.new
@category = @report.build_category
@quetions = @category.questions.build
@questions.answers.build
But without associations reports with categories i cannot do it. I have error like categories.report_id does not exist What I'm doing wrong?
My associations:
Category => has many => Questions
Questions => has many => Answers
My db schema:
Reports:
user_id: integer
category_id:integer
Category:
title: string
slug: string
Question:
title: string
category_id: integer
Answer:
title: string
question_id: integer
Upvotes: 0
Views: 851
Reputation: 2784
I recommend using the NestedForm Gem (https://github.com/ryanb/nested_form)
gem 'nested_form'
You need to be doing something like the following in controller:
@report= Report.new
@report.build_category
Then in view:
<%= 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 %>
Upvotes: 1