/ RAILS

Rails routes difference between resource and resources

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 when selecting resource or resources when generating routers.

Use of resources in Rails routes

Let’s see the routes generated when we use resources in Rails routes.

resources :products
HTTP Verb Path Controller#Action Used for
GET /products products#index display a list of all products
GET /products/new products#new return an HTML form for creating a new product
POST /products products#create create a new product
GET /products/:id products#show display a specific product
GET /products/:id/edit products#edit return an HTML form for editing a product
PATCH/PUT /products/:id products#update update a specific product
DELETE /products/:id products#destroy 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. Thus,

  • To view profile, route should be something like www.example.com/profile
  • To edit profile, route should be something like www.example.com/profile/edit

etc.

We can define routes for profile resource as given below.

resource :profile
HTTP Verb Path Controller#Action Used for
GET /profile/new profiles#new return an HTML form for creating a new profile
POST /profile profiles#create create a new profile
GET /profile profiles#show display a specific profile
GET /profile/edit profiles#edit return an HTML form for editing a profile
PATCH/PUT /profile profiles#update update a specific profile
DELETE /profile profiles#destroy 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.

Rails guides suggests:,

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 resources generated one extra route for index action. index action 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.

References

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee