At the routing level, there are two methods that can be used to declare the routes: singular and plural.
Routes are generally defined as plural using the plural resources
.
Singular routes* are a little different – they are written as singular resource
.
Declaring a resource
or resources
generally corresponds to generating many default routes.
For example:
resources :profiles
resource :profile
resource
is singular. resources
is plural.
Plural resources are most commonly used. So, to understand singular resources think of this example: You are designing a social media platform. As a Facebook or LinkedIn user, if you click on your profile, you want the application to show your own profile. This is a common scenario that you can solve using singular resources.
We can define the profiles of users in our database, but we only need to view the profile so, therefore, we do not need all the other routes. Hence, we just generate the show
route:
resources: profiles, only: show
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.
A user can add a simple declaration with:
resource :profile, only: :show
This creates a route for a single profile
and is done without changing any controller code. Now, the users have been enabled to access each other’s profiles.
resources :profiles, only: :show do
resource :profile, only: :show
end
Because you might want to use the same controller for a singular route (/account) and a plural route (/accounts/45), singular resources map to plural controllers. This is so, for example, resource :photo and resources :photos will create both singular and plural routes that map to the same controller (PhotosController).
This implementation is called plural to singular route. It creates a profiles_profile
route for a user to access the profiles of other users.
Free Resources