Resource route in ruby and rails
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
stephen
Updated on June 04, 2022Comments
-
stephen almost 2 years
I have
resources :blog
declared in my
routes.rb
file but when I try to accessblog_path
in a controller or ahtml.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 methodshow
with ashow.html.erb
file in the views directory. If I define:match '/blog', to: 'blog#show', via: 'get'
instead, thenblog_path
works fine.My understanding is resources:
blog
is just syntactic sugar formatch '/blog', to: 'blog#show', via: 'get'
and a bunch of other routes. Please help. -
stephen about 10 yearsdoes this mean that all resources must end with an 's'? Like resources: photos, resources: blogs