The other day, I summarized the differences between resources and resources, but there were some points to note when using them in combination, so I summarized them. Click here for the difference → Difference between resources and resources --Qiita
By using resources in combination, you can easily generate the following routing.
--List display of all users --Detailed display of all users --Detailed display of own user --Editing your own user information
Anyone can view the list of all users and the details of each user, but only their own can edit user information.
config/routes.rb
resources :users, only: [:index, :show]
resource :user, only: [:show, :edit, :update]
Looking at the routes generated by rails routes, it looks like the following.
Terminal
Prefix Verb URI Pattern Controller#Action
users GET /users(.:format) users#index
user GET /users/:id(.:format) users#show
edit_user GET /user/edit(.:format) users#edit
GET /user(.:format) users#show
PATCH /user(.:format) users#update
PUT /user(.:format) users#update
ʻUser GET / users /: id (.: format) The user_path part of users # show` is assigned to / users /: id, so the helper method that should return / user is not generated. So, I tried to describe it in reverse order.
config/routes.rb
resource :user, only: [:show, :edit, :update]
resources :users, only: [:index, :show]
Looking at the routes generated by rails routes, it looks like the following.
Terminal
Prefix Verb URI Pattern Controller#Action
edit_user GET /user/edit(.:format) users#edit
user GET /user(.:format) users#show
PATCH /user(.:format) users#update
PUT /user(.:format) users#update
users GET /users(.:format) users#index
GET /users/:id(.:format) users#show
If the local user can be identified by the login function (session management), it is not necessary to include: id in the request, so the routing for the local user uses resource.
In order to see the details screen of users other than yourself, it is necessary to specify the ID of the target user, so resources is generating a route that includes: id in the request.
When creating a route by combining resource used in the singular and resources used in the plural, write the singular resource above.
Recommended Posts