Resource routing in Rails

Tram Ho

What is Rails Routes ? Where will the user’s request be sent? What is the connection between Rails routes, Controller and View? What is Rails RESTful? …

These are the questions many people have when starting out with Ruby on Rails, this article will explain the most basic questions above and give examples using some Ruby on Rails techniques to Help you understand Rails Routes better .

1. What is Rails Router?

The Rails route is a module that detects URLs (requests) from the browser, it needs to know that each request runs corresponding to an action in the Controller. To put it simply, when a user enters a url in your domain name, Rails routes will call the correct Controller and action corresponding to that url. If no route is found matching the request, the application will occur. error. In addition, the router generates Paths and URLs from the code so that users can quickly link to the path they want.

In the diagram above, the user’s request for the URL pages/home will go from the user’s browser to the Rails Router . The routes will then determine that the above request will be handled by pages_controller.rb and the corresponding home action. Finally a response is returned to the user (the controller renders the HTML back to the user).

The Rails application requires routes to match the user’s request and the action trong controller corresponding action trong controller . The routes in a Rails application are configured in the config/routes.rb file. In the diagram above the corresponding routes are:

To check routes in your application, use the rails routes command.

The route will automatically map the request from the browser to the corresponding action or method of pages_controller . The action then determines which page will be shown to the user (here the page displayed is home.html.erb .

2. Rails RESTful

REST stands for Representational State Transfer, and in simple terms REST is an architecture in website programming. The RESTful application will treat the web as a resource . There are basically 7 types of action you can take with a resource .

  • GET: index, show, new and edit
  • POST: create
  • PUT: update
  • DELETE: destroy

In Rails you can create RESTful default routes by using the resources keyword followed by the name of the corresponding controller, for example:

The above command creates all 7 routes mapped to controller users .

Use the rails routes command to check.

3. Resource routing

3.1. CRUD, Verbs and Actions

Each routes has a mapping between HTTP verbs and URLs to control actions. As the example above.

Create 7 different routes, all mapped to the Users controller.

HTTP VerbPathController # ActionUser for
GET/ usersusers # indexShow all users
GET/ users / newusers # newReturns the HTML form to create a new user
POST/ usersusers # createCreate a new user
GET/ users /: idusers # showDisplays a user
GET/ users /: id / editusers # editReturns the HTML form to edit the user
PATCH / PUT/ users /: idusers # updateUpdate a user
DELETE/ users /: idusers # destroyDelete a user

Explain a little bit about the table above 😄

  • HTTP Verb is the method name.
  • Path is the path that will display in the browser when you perform an action, for example, the GET method with the path is / users /: id will perform the show action to display the user information that id is transmisson in.

3.2 Path and URL helper

Creating a resourceful route also creates some helper for the controller in your application. That is the path and url , In the case of resources :users we have:

  • users_path: returns all users
  • new_user_path: returns user / new
  • edit_user_path (: id): Returns / user /: id / edit
  • user_path (: id) Returns / users /: id

3.3 Controller Namespaces and Routing

Rails allows you to group controllers into a namespace using the namespace keyword. For example, group of Articles and Comments controllers in the Admin controller.

Meanwhile, to view the article you must add the admin prefix to the url.

There will still be 7 routes generated as follows:

HTTP VerbPathController # ActionNamed Helper
GET/ admin / articles/ admin / articles # indexadmin_articles_path
GET/ admin / articles / new/ admin / articles # newnew_admin_articles_path
POST/ admin / articles/ admin / articles # createadmin_articles_path
GET/ admin / articles /: id/ admin / articles # showadmin_articles_path (: id)
GET/ admin / articles /: id / edit/ admin / articles # editedit_admin_articles_path (: id)
PATCH / PUT/ admin / articles /: id/ admin / articles # updateadmin_articles_path (: id)
DELETE/ admin / articles /: id/ admin / articles # destroyadmin_articles_path (: id)

3.4 Limit the route you want to use

Rails allows developers to select the action they want to use using keywords like only or except . For example:

With the above configuration, with post you only have 2 routes corresponding to the index and show that is the effect of only . In contrast, when using except with the user you will have all routes by default of RESTful except routes corresponding to the index easy to understand, 😄 .

3.5 Non-RESTful Routes

RESTful is the default choice for a Rails application, but you can also create your own routes and map it to a controller.

However, when possible, you should still try to comply with RESTful 😄 .

3.6 Resources or Resource?

Since the beginning of the article, all of my examples have used resources so you already understand what resources do in the Rails application, right? But in Rails also gives programmers a way to create from routes near the same resources that resource . This section will highlight the differences between resources and resource .

First, let’s see the difference between these 2 options!

With resources

Results of rails routes .

As you know, the resources provided to developers with 7 routes are: index, new, create, show, edit, update, destroy in accordance with RESTful architecture to support interaction with the database.

With resource

Results of rails routes

As for resoucre , there are only 6 routes left: new, create, show, edit, update, destroy . And it’s also evident in routes do not use :id .

So when to use resoucre ?

For example: When the person you want for users to be able to view their information without an id , then your link is simply /profile , which can also display the information of the currently logged in user. .

3.6 Nested Resources

Nested Resources is a technique in Rails that reflects the has_many relationship between model in routes and then routes it via URLs. Using Nested Resources makes code easier to understand, helping code DRY (don’t repeat yourself). The following example will help you better understand Nested Resources .

A club will have many fighters and a fighter will belong to a club .

In the config/routes.rb file, we configure the following:

Now that we have Nested Resources in our app, check those routes ~

Done! So Rails still creates fully RESTful routes , and it will have the clubs/:club_id exactly what we want.

Go here instead of having to code like this in the clubs_controller.rb file.

Then we can code and still follow the principles of the RESTful architecture, in the file fighters_controller.rb we write:

4. Conclusion

The above are the basics of Rails Routing in Rails that I have learned. Hopefully through this article you will understand more about Rails Routing in Rails.

Thanks for reading!

Reference source:

https://guides.rubyonrails.org/routing.html#nested-resources https://dev.to/brittanytinnin/nested-resources-in-rails-5-4oea https://stackoverflow.com/questions/11356146/ difference-between-resource-and-resources-in-rails-routing

Share the news now

Source : Viblo