[Ruby] I summarized the points to note when using resources and resources in combination

1 minute read

The other day, I tried to summarize the difference between resources and resources, but there were some notes when using them in combination, so I summarized them. Click here for the difference → Difference between resources and resources-Qiita

When using a combination of resources and resources

By using resources and resources in combination, you can easily generate the following routes.

  • List all users
  • Detailed display of all users
  • Display your own details
  • Edit own user information

Everyone can view the list of all users and details of each user, but only the user can edit the user information.

config/routes.rb


  resources :users, only: [:index, :show]
  resource :user, only: [:show, :edit, :update]

When you check the route 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

Since user GET /users/:id(.:format) users#show and user_path are assigned to /users/:id, the helper method that should return /user is not generated. So, I wrote it in reverse order.

config/routes.rb


  resource :user, only: [:show, :edit, :update]
  resources :users, only: [:index, :show]

When you check the route 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 own user can be identified by the login function (session management), it is not necessary to include :id in the request, so the route regarding the own user uses resource.

Since it is necessary to specify the ID of the target user in order to see the details screen of users other than yourself, resources generates a route that includes :id in the request.

Conclusion

When making a route by combining the resource used in the singular form and the resources used in the plural form, write the singular form of resource above.

Tags: ,

Updated: