我使用生成器来构建类别和问题。
my routes.rb
resources :categories do
resources :questions do
resources :choices, only: [:index]
end
end
我尝试添加或编辑问题时出现问题。
这是我的部分形式,然后才能确定关系正常。
<%= form_for [@question.category, @question] do |f| %>
<% if @question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% @question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :question_type %><br>
<%= f.text_field :question_type %>
</div>
<div class="field">
<%= f.label :explanation %><br>
<%= f.text_field :explanation %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.label :category_id %><br>
<%= f.text_field :category_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我必须改变它才能发挥作用?现在我明白了,
undefined method `questions_path'
答案 0 :(得分:2)
试试这个
<强>更新强>
控制器
@category = Category.find(params[:category_id])
@question = @category.questions.new
_form
<%= form_for([@category, @question]) do |f| %>
答案 1 :(得分:1)
将此行添加到您的category.rb
模型文件中:
accepts_nested_attributes_for :questions
另外,在您的控制器中:
@category = Category.find(params[:category_id])
@question = Question.new(category: @category)
并形成:
<%= form_for([@category, @question]) do |f| %>
答案 2 :(得分:1)
您应该传递父对象,然后为新对象构建子对象。
<%= form_for [@category, @category.questions.build] do |f| %>
编辑:
<%= form_for [@category, @category.questions.first_or_your_object] do |f| %>
像这样:
<% if @category.new_record? %>
<%= form_for [@category, @category.questions.build] do |f| %>
<% else %>
<%= form_for [@category, @category.questions.first_or_your_object] do |f|
<% else %>
同时添加您的类别模型:
accepts_nested_attributes_for :questions