Search code examples
ruby-on-railsrubysimple-form-for

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


I have a form which is part of a "comments" object, which is the child of a "post" object which in turn is the child of a "Category" object, I get the above error message with the following code (using simple_forms) Any advice?

= 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

Solution

  • You have defined your comments route under posts, which is nested under categories. With proper indentation, the error is easy to see:

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

    So you have a categories_posts_comments_path.

    If you run rake routes in the console you should see an output of all you existing routes. If you don't want this behaviour:

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

    But beware that this will duplicate a lot of routes, so you will want to use the only or except arguments to limit the number of routes generated.