Rails provides RESTful routing for resources. Routes can either define single resource or plural resources to generate routes of the application.
There is a logical difference that should be considered
resources when generating routers.
Use of resources in Rails routes
Let’s see the routes generated when we use
resources in Rails routes.
|display a list of all products
|return an HTML form for creating a new product
|create a new product
|display a specific product
|return an HTML form for editing a product
|update a specific product
|delete a specific product
Use of resource in Rails routes
Let’s take an example of user
profile for a user logged in on website using Rails application.
User profile is supposed to be an entity (resource) to be worked on when user is logged in.
We would would not want end user to know the profile
ID of the user.
- To view profile, route should be something like
- To edit profile, route should be something like
We can define routes for
profile resource as given below.
|return an HTML form for creating a new profile
|create a new profile
|display a specific profile
|return an HTML form for editing a profile
|update a specific profile
|delete a specific profile
We can see singular resource routes don’t have
ID of the resource.
Moreover, it still directs requests to pluralized controller name.
Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like /profile to always show the profile of the currently logged in user. In this case, you can use a singular resource.
Difference between resource and resources
- As we can see
resourcesgenerated one extra route for
indexaction is intended to display list of resource.
- Singular routes don’t have ID of resource being worked on.
- Both singular and plural resource routes route request to pluralized controller.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox