user11406 user11406 - 1 month ago 5
Ruby Question

Route to /post/new instead of /posts/new in rails?

This is related to a question I asked here: undefined method `posts_path' for #<#<Class:0x007fe3547d97d8>:0x007fe3546d58f0>

I was told to switch my controllers, view etc from "post" to "posts" which fixed the issue, however if I did want to use the URL /post/new, how would I do that without receiving the "undefined method `posts_path'" error I was before?

I don't understand why it's looking for "posts_path" when my controller, model and view are all called "post".

RSB RSB
Answer

Add this before resources :posts line/block in routes.rb file,

get '/post/new', to: 'posts#new'

When you define routes using resources :posts, by default the route to the new action is /posts/new, So to override the same you need to define custom route like I did above. Also, to search the routes, Rails scans the routes.rb file from top to bottom, whatever matches first is taken. Therefore, to override the default behaviour, I asked you to define this custom route before the default routes.

Hope that helps!

Comments