Ruby on Rails Routes

Learn via video courses
Topics Covered

Overview

Have you ever wondered how you can access a website by typing a URL into a browser? This is where the concept of routes comes in. Just like how we use maps to navigate in the real world, web applications use routes to direct incoming requests to the appropriate controller actions or views. By understanding and managing routes in the rails environment effectively, we can build powerful and dynamic web applications.

What is Routing

In Ruby on Rails, the simple process of mapping a URL to a function is referred to as routing or routes in Rails. Whenever we type a URL into the browser the router recognizes the URL and executes the mapped function.

Purpose of Rails Router

Each incoming HTTP request is handled by the routes in rails and is directed to a controller's action. It essentially helps us in creating various URLs for our web application as well as mapping those URLs to their respective functions.

Imagine it like a mapping for all the possible requests to our web application with their corresponding controller actions or views. Let's take an example of a blog website that allows users to create, edit, view, and delete blog posts. Let's say our application receives an incoming request for:

It asks the router to match it to a controller action. If the first matching route is:

Then, the request is processed by the show action in the PostController to which id 15 is passed as params.

How Routing is done in Ruby on Rails?

In Ruby on Rails, routing is done through the config/routes.rb file, which is located in the root directory of our Rails application. As we know, this film gives us mapping for all the requests to controller actions and views.

We just need to add the required rails routes to our config/routes.rb file to map the URL to each view and action inside the controller.

Now our blog application is ready to handle HTTP requests. In the above example:

  • posts#index is the root or the home page of the website.
  • get 'posts' maps the /posts route to the index action of PostsController.
  • get posts/new maps posts/new route to new action of PostsController.
  • get 'posts/:id' maps get the request of a post with an id to show action of PostsController.
  • post 'posts' maps /posts route to create action of PostsController.
  • patch 'posts/:id' maps update request of a post with an id to update action of PostsController.
  • delete 'posts/:id' maps delete request of a post with an id to destroy action of PostsController.

Types of HTTP Requests

Five types of HTTP requests can be created:

  1. GET: This request is used to retrieve data from the server. When a user visits a web page, a GET request is sent to the server to retrieve the page's HTML, CSS, and JavaScript files.
  2. POST: This request is used to submit data(add entity) to the server, such as form data or JSON data. When a user submits a form, a POST request is sent to the server with the form data.
  3. PUT: This request is used to update data(replace existing entity) on the server. For example, if a user edits their profile information, a PUT request would be sent to the server to update the information.
  4. DELETE: This request is used to delete data from the server. For example, if a user wants to delete a post, a DELETE request would be sent to the server to delete the post.
  5. PATCH: This request is similar to PUT, but it is used to update only a portion of the data on the server. For example, if a user updates their profile picture, a PATCH request would be sent to the server to update only the profile picture.

Types of HTTP Requests These methods determine which controller action method is called through routes in rails.

Decoding HTTP Requests

When we go to a particular blog post with a post id, let's say 1, then the below request would be made:

Corresponding to this request we'll have a rails route in configs/routes.rb

This route in rails calls the show action in the PostsController and passes the id parameter as an argument. Here's an example of the show action:

The show action retrieves the post with the corresponding id using the Post. find action and assigns it to an instance variable @post. Now it can be rendered to a view to display the contents of @post. For example, we could create a show.html.erb template in the app/views/posts directory that displays the post's title and content:

Resourceful and Non-Resourceful Routing

Resourceful Routing

For a given resourceful controller, resource routing enables us to simply declare all of the common rails routes. We may specify all of the required routes for index, show, new, edit, create, update, and destroy actions with just one call to resources. Resourceful routes can be defined in the config/routes.rb file. For example, the following code defines resourceful routes for a posts resource:

The above line will provide the following auto-generated routes:

Non-Resourceful Routing

Apart from resourceful routing, Rails also allows the routing of custom URLs to specific actions in the controller. This type of routing is known as Non-Resourceful routing. Unlike resourceful routing, we need to manually set up each custom route within our application.

Non-resourceful routes are defined using the HTTP verbs and are matched to specific controller actions. For example:

This will generate the following routes:

In the above example sessions#new give us controller and action information, where sessions is the controller and new, create, destroy are the actions of the controller.

Customizing Resourceful Routing

  1. The seven rails routes that the resources method generates for us are not always what we want. To filter out the routes as per our needs, we can pass
  • only: includes rails routes for only the mentioned actions.
  • except: excludes rails routes for the mentioned actions. For example,
  1. The :as option let us override the normal naming for the named route helpers. For example:
  1. The :controller option lets us explicitly specify a controller to use for the resource. For example:

In this example, we are specifying the controller option to use the blogs controller instead of the default posts controller for handling requests related to the posts resource.

Defining Resources

Resources are defined in the config/routes.rb file. The basic syntax for defining a resource in Rails is:

  1. Single & Multiple Resources The resources method can be used to define a single resource or multiple resources. For example:
  1. Nested Resources Nested resources allow us to define a hierarchical relationship between resources in our application. For example, a blog post may have many comments:

This will generate routes for comments nested under posts:

Inspection and Testing of Rail Routes

  • Inspecting Rails Routes To fetch all the routes rails, run the below command in the terminal:

The following output is shown in the terminal:

We can also visit http://localhost:3000/rails/info/routes to get all the routes in the rails application.

  • Testing Rails Routes We should incorporate rails routes into our testing process (just like the rest of our application). Three built-in assertions in Rails are available to make testing routes easier:
    1. assert_generates: This method asserts that a given set of options can generate a specific path. It is useful for testing custom route rails and is used to verify if the routing system is properly generating the expected URL. For example:
    1. assert_recognizes: It is used to test that incoming requests are correctly routed to the expected controller's action based on the URL path. For example:
    1. assert_routing: It is a method that checks if a set of options will generate a specific path and also that the generated path can be parsed back into the expected set of parameters. It's like a combination of assert_generates and assert_recognizes methods in a single test. For example:

FAQs

Q: How do I define a route in Rails?

A: We can define rails routes using the routes.RB file in our application's config directory. Use the get, post, put, patch, and delete methods to define routes for different HTTP methods.

Q: What is resourceful routing in Rails?

A: Resourceful routing is a convention in Rails that maps HTTP requests to CRUD actions on a resource, such as a model or a database table. It provides a standard set of routes for a resource, such as an index, show, new, create, edit, update, and destroy.

Q: What is nesting in Rails routes?

A: Nesting allows you to define routes for resources that are related to other resources. For example, you can nest comments routes within posts routes to handle comments that belong to specific posts.

Conclusion

  • The process of assigning incoming HTTP requests to controller actions and views is referred to as routing or routes in rails.
  • Routing is done through the config/routes.rb file, which is located in the root directory of our Rails application.
  • There are five types of HTTP requests put, post, get, patch, and delete.
  • Routes can be implemented in two ways, namely resourceful routing, and non-resourceful routing.
  • We can use various testing methods such as assert_generates, assert_recognizes, and assert_routing to test our rails routes.