I'm trying to build 2 nested forms with Cocoon which works fine. I have a Game model which has many Questions and a Question has many Answers.
# Game model
class Game < ApplicationRecord
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions, allow_destroy: true
end
# Question model
class Question < ApplicationRecord
belongs_to :game
has_many :answers, dependent: :destroy
validates :text, presence: true
accepts_nested_attributes_for :answers, allow_destroy: true
end
# Answer model
class Answer < ApplicationRecord
belongs_to :question
end
the link_to_add_association link works everywhere, the link_to_remove association link works fine in _question_fields partial view but I have
`"undefined method `new_record?' for nil:NilClass"`
error when I insert the link_to_remove_association in _answer_fields partial view. I'm sure that it's an error on my part but I can't retrieve where.
<%= form_with(model: @game, url: games_path, local: true ) do |form| %>
<div class="form-group game">
<%= form.label(':name', "Title") %>
<%= form.text_field ':name', class: 'form-control form-control-sm' %>
</div>
<div class="wrapper-questions"></div>
<%= form.fields_for :questions do |question_form| %>
<%= render 'games/partials/question_fields', f: question_form %>
<% end %>
<div class="row form-actions links">
<div class="col-sm">
<%= link_to_add_association 'Add a question',
form,
:questions,
:partial => 'games/partials/question_fields',
class: "btn btn-secondary",
'data-association-insertion-node' => '.wrapper-questions'
%>
</div>
<div class="col-sm text-right">
<%= form.submit 'Save', :class => "btn btn-primary" %>
</div>
</div>
<% end %>
<div class="question-wrapper jumbotron nested-fields">
<%= link_to_remove_association f, { class: 'btn btn-light' } do %>
<i class="fa fa-trash" aria-hidden="true"></i> Delete the question
<% end %>
<p><strong>Question</strong></p>
<div class="form-group">
<strong><%= f.label(:text, 'Question:') %></strong>
<%= f.text_field :text, class: "form-control" %>
</div>
<%= f.fields_for :questions do |answer_form| %>
<%= render 'games/partials/answer_fields', f: answer_form %>
<% end %>
<div class="row">
<div id="wrapper-answers"></div>
<div class="col-sm">
<%= link_to_add_association 'Add an answer',
f,
:answers,
:partial => 'games/partials/answer_fields',
data: { 'association-insertion-method' => :prepend },
class: "btn btn-secondary"
%>
</div>
</div>
</div>
<div class="row nested-fields">
<div class="col">
<%= f.text_field :text, class: "form-control" %>
</div>
<div class="col">
<label class="btn btn-secondary form-control">
<%= f.check_box :correct %>
</label>
</div>
<!-- My error is here -->
<%= link_to_remove_association 'remove answer', f %>
</div>
Does anybody have an idea what I'm doing wrong ? Regards, Lilith
In partials/_question_fields.html.erb
<%= f.fields_for :questions do |answer_form| %>
Should likely be :
<%= f.fields_for :answers do |answer_form| %>