Resource route in ruby and rails

10,418

Solution 1

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

Solution 2

Make resource plural like this resource :blogs

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

This is rails standard

Share:
10,418
stephen
Author by

stephen

Updated on June 04, 2022

Comments

  • stephen
    stephen almost 2 years

    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.

  • stephen
    stephen about 10 years
    does this mean that all resources must end with an 's'? Like resources: photos, resources: blogs