ruby-on-railsrails-routingnested-resources

how to modify form_with when using nested resources in rails


I am learning to use nested resources in rails. To keep it simple and reproducible I have setup a very simple blog app with two resources posts and comments. Most of the code has been generated by scaffold.

I have successfully modified post#show to display comments below each post, the link to Add New Comment also renders the new comment form. However I can not save the comments and get a routing error:

ActionController::RoutingError (No route matches [POST] "/posts/1/comments/new"

A comparison of the comment partial form

original/before nesting resources:

<%= form_with(model: comment, local: true) do |form| %>

modified/after nesting resources:

<%= form_with(url: new_post_comment_path, 
    scope: :comment, local: true) do |form| %>

I have pushed the code to github repo, with separate branches master without nested resources and nestedRoutes with nested resources. Will appreciate help of the community.

Note: Answers to Nested Resources w/ Rails 5.1 form_with did not work for me.


Solution

  • It looks like the url you are passing is the new_post_comment_path, when you probaby want your form to go the create path. Based on your routes I assume this looks like post_comments_path.

    That’s why you get the error you see, there is no POST method defined for the new path (only GET).