#<#<Class:0xa3ddb8c>:0xb501ae4> 的未定义方法“post_comments_path”

undefined method `post_comments_path' for #<#<Class:0xa3ddb8c>:0xb501ae4>

我有一个表单,它是 "comments" 对象的一部分,它是 "post" 对象的子对象,而 "post" 对象又是 "Category" 对象的子对象,我得到上面的错误消息和以下代码(使用 simple_forms)有什么建议吗?

= simple_form_for([@post, @post.comments.build], html: {class: 'form-horizontal'}) do |f| 
= f.input :comment, label: "Your Reply", input_html: {class: "form-control"} 
= f.submit

routes.rb:

Rails.application.routes.draw do
devise_for :users
resources :categories do
resources :posts do
resources :comments
end
end

root 'categories#index'
end

您已在 posts 下定义了 comments 路线,该路线嵌套在 categories 下。适当缩进,错误很容易看到:

Rails.application.routes.draw do
  resources :categories do # Everything is nested under here
    resources :posts do
      resources :comments
    end
  end
end

所以你有一个 categories_posts_comments_path.

如果您在控制台中 运行 rake routes,您应该会看到所有现有路由的输出。如果您不想要这种行为:

  resources :posts do
    resources :comments
  end

  resources :categories do # Everything is nested under here
    resources :posts
  end

但请注意,这会重复很多路由,因此您需要使用 onlyexcept 参数来限制生成的路由数量。

结果我不得不将 link 更改为:

= simple_form_for([@category, @post, @post.comments.build], html: {class: 'form-horizontal'}) do |f| 

并将路线更改为:

Rails.application.routes.draw do
devise_for :users
  resources :categories do
    resources :posts
  end
  resources :posts do
    resources :comments
  end

  root 'categories#index'
end