Form_For 助手中未定义的方法

Undefined Method in Form_For Helper

我有一个 post 模型,belongs_to 一个 category 模型。 post 资源嵌套在类别资源下。我正在构建一个 form_for @post 来创建一个新的 post。但是,我收到以下错误:

undefined method 'posts_path' for #<#<Class:0x007fd54ba33540>:0x007fd54c8e57c8>

根据我的路线,它应该指向 new_category_post_path 但我不确定为什么不是。我尝试了 here 提出的解决方案,因为它与我的情况非常相似,但无济于事。有什么想法吗?

routes.rb:

resources :categories do
  resources :posts
end

app/models/category.rb 和 post.rb:

class Category < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :category
end

app/controllers/posts_controller.rb:

class PostsController < ApplicationController    
  def new
    @category = Category.find(params[:category_id])
    @post = @category.posts.new
  end
end

views/posts/new.html.erb:

<%= form_for @post do |f| %>
  <%=f.text_field :title, placeholder: 'Title...' %>
  <%=f.text_area :content %>
  <%=f.submit 'Create post' %>
<% end %>

rake 路线:

            Prefix Verb   URI Pattern                                       Controller#Action
    category_posts GET    /categories/:category_id/posts(.:format)          posts#index
                   POST   /categories/:category_id/posts(.:format)          posts#create
 new_category_post GET    /categories/:category_id/posts/new(.:format)      posts#new
edit_category_post GET    /categories/:category_id/posts/:id/edit(.:format) posts#edit
     category_post GET    /categories/:category_id/posts/:id(.:format)      posts#show
                   PATCH  /categories/:category_id/posts/:id(.:format)      posts#update
                   PUT    /categories/:category_id/posts/:id(.:format)      posts#update
                   DELETE /categories/:category_id/posts/:id(.:format)      posts#destroy
        categories GET    /categories(.:format)                             categories#index
                   POST   /categories(.:format)                             categories#create
      new_category GET    /categories/new(.:format)                         categories#new
     edit_category GET    /categories/:id/edit(.:format)                    categories#edit
          category GET    /categories/:id(.:format)                         categories#show
                   PATCH  /categories/:id(.:format)                         categories#update
                   PUT    /categories/:id(.:format)                         categories#update
                   DELETE /categories/:id(.:format)                         categories#destroy
              root GET    /                                                 categories#index

如果你想嵌套你的资源,那么你需要确保在 form_for 助手中生成的 URL 知道如何正确地做到这一点。在这种情况下,您需要向它传递 2 个对象,即 post 对象和类别对象。位置是第一个,新对象在数组中是第二个,所以你的形式看起来更像:

<%= form_for [@category,@post] do |f| %>
  <%=f.text_field :title, placeholder: 'Title...' %>
  <%=f.text_area :content %>
  <%=f.submit 'Create post' %>
<% end %>