Question

I have

resources :blog

declared in my routes.rb file but when I try to access blog_path in a controller or a html.erb file, I get the following error:

No route matches {:controller=>"blog", :action=>"show"} missing required keys: [:id]

I have created a controller called BlogController and defined the method show with a show.html.erb file in the views directory. If I define:

match '/blog', to: 'blog#show', via: 'get' instead, then blog_path works fine.

My understanding is resources: blog is just syntactic sugar for match '/blog', to: 'blog#show', via: 'get' and a bunch of other routes. Please help.

Was it helpful?

Solution

blog_path is for generating path to a blog, so you need id or a blog object, this helper generates path like /blogs/12 to blogs#show, and blogs#show is for showing an object. blogs_path generates /blogs to blogs#index (like to all blogs).

Look at 2 Resource Routing: the Rails Default

resources :photos

GET        /photos           index    display a list of all photos
GET        /photos/new       new      return an HTML form for creating a new photo
POST       /photos           create   create a new photo
GET        /photos/:id       show     display a specific photo
GET        /photos/:id/edit  edit     return an HTML form for editing a photo
PATCH/PUT  /photos/:id       update   update a specific photo
DELETE     /photos/:id       destroy  delete a specific photo

You have used resources :blog without s. It generates

            blog_index GET    /blog(.:format)                                          blog#index
                       POST   /blog(.:format)                                          blog#create
              new_blog GET    /blog/new(.:format)                                      blog#new
             edit_blog GET    /blog/:id/edit(.:format)                                 blog#edit
                  blog GET    /blog/:id(.:format)                                      blog#show
                       PUT    /blog/:id(.:format)                                      blog#update
                       DELETE /blog/:id(.:format)                                      blog#destroy

OTHER TIPS

Make resource plural like this resource :blogs

And make controller name blogs_controller.rb and its class name BlogsController

This is rails standard

I'm recently starting to use Rails, but I noticed that when Rails generates a controller for me, it names it with an underscore between the name and the word controller.

Something like blog_controller.rb. A few days ago I replaced one with other without the underscore and get a similar error, not sure why.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top