嵌套路由 form_for 部分不适用于新操作和编辑操作 - Rails 4

Nested routes form_for partial not working for new and edit actions - Rails 4

我使用生成器来构建类别和问题。

我的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'

试试这个

更新

控制器

@category = Category.find(params[:category_id])
@question = @category.questions.new

_表格

<%= form_for([@category, @question]) do |f| %>

Reference

将此行添加到您的 category.rb 模型文件中:

accepts_nested_attributes_for :questions

此外,在您的控制器中:

@category = Category.find(params[:category_id])
@question = Question.new(category: @category)

并形成:

<%= form_for([@category, @question]) do |f| %>

您应该传递父对象,然后为新对象构建子对象。

<%= 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