Something about Rails routes

Tram Ho

The resources feature in routes is very useful, but when starting with RoR, some features built on top of it can be difficult to interpret for yourself. The article will help you understand and be able to use routes effectively!

basic information about resources

Resources help you to write a concise but complete description of the basic routes in your application. When you define a resources route , it will create routes for all CRUD actions for you according to rails conventions .

resource and resources

The first obvious difference between resources and resources is s , which means that the resource is plural or singular.

Routes are created with resources : 7 routes

PrefixVerbURI PatternController # action
usersGET/users(.:format)users # index
POST/users(.:format)users # create
new_userGET/users/new(.:format)users # new
edit_userGET/users/:id/(.:format)users # edit
userGET/users/:id/(.:format)users # show
PUT / PATCH/users/:id/(.:format)users # update
DELETE/users/:id/(.:format)users # destroy

Meanwhile, the Routes are created with the resource :

PrefixVerbURI PatternController # action
new_user sGET/users/new(.:format)users # new
edit_user sGET/users/(.:format)users # edit
usersGET/users/(.:format)users # show
PUT / PATCH/users/(.:format)users # update
DELETE/users/(.:format)users # destroy
POST/users(.:format)users # create

As you can see there is no ID in route pattens when using resource and resource does not generate any route but is processed with action index.

So when to use resource ?

Ez! Sometimes you look up without referring to the ID. For example, you want /profile always show the profile of the currently logged in user. In this case, you can use singular resource to map /profile (instead of /profile/: id ) to action show . Or for another example, a user usually belongs to a single organization, so to view that organization’s profile, we can have 2 routes:

  1. /organizations/:id
  2. /organization #simply

Here, the second way of implementing the route makes more sense, right? You get the organization object from association with user:

only and except

If you want to have only specific resource (s) routes, you can add the exceptions under “only” or “except”.

Generated Routes would be:

collection route?

By using the collection, you can add additional routes to the controller. You just need to create a new collection route and define a method with the same name as the method on the controller. As you can see both ways of making COLLECTION work:

member in route?

member are like collection but they have an id in the generated route, which means that the route belongs to a member of the resource

And there are also two ways of creating MEMBER:

Alright! By using these methods, your code will be cleaner and more readable.
See you in the next post!

Reference

  1. Maybe you don’t know these about Rails routes!
  2. Routing in Rails
  3. Routing
Share the news now

Source : Viblo