我正在尝试使用Cocoon构建2个嵌套表单,这样可以正常工作。我有一个游戏模型,它有很多问题,一个问题有很多答案。
# 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
link_to_add_association链接无处不在,link_to_remove关联链接在_question_fields局部视图中正常工作但我有
`"undefined method `new_record?' for nil:NilClass"`
在_answer_fields局部视图中插入link_to_remove_association时出现错误。我确信这是我的错误,但我找不到。
<%= 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>
有人知道我做错了什么吗? 问候, 莉莉丝
答案 0 :(得分:1)
在partials/_question_fields.html.erb
<%= f.fields_for :questions do |answer_form| %>
应该是:
<%= f.fields_for :answers do |answer_form| %>