Introduction to Routing in Rails

Tutorial 1 of 5

1. Introduction

1.1 Brief Explanation of the Tutorial's Goal

In this tutorial, we aim to provide a comprehensive introduction to Routing in Rails. Our goal is to help you understand how Rails maps URLs to controller actions, and how you can manipulate this mapping to suit your application's needs.

1.2 What the User Will Learn

By the end of this tutorial, you will be able to:
- Understand the basic concepts of Rails Routing.
- Customize URL paths in your Rails application.
- Map URLs to specific controller actions.

1.3 Prerequisites

For this tutorial, you should have a basic understanding of:
- Ruby programming language.
- Rails framework.
- MVC (Model-View-Controller) architecture.

2. Step-by-Step Guide

2.1 Understanding Rails Routing

Rails Routing is a mechanism that determines how an application responds to a browser request. It works by connecting incoming URLs to a controller action. A controller action, in turn, handles the request and sends back a response to the client.

2.2 Defining Routes

Routes are defined in the config/routes.rb file. A simple route definition looks like this:

get 'welcome/home', to: 'welcome#home'

In this example, the get method defines a route that maps a GET request to the URL /welcome/home to the home action in the WelcomeController.

2.3 Routing Best Practices

  • Try to keep your routes.rb file as clean and understandable as possible.
  • Make use of resource routing to declare all common routes for a given resource in a single line of code.
  • Avoid non-RESTful routes as much as possible.

3. Code Examples

3.1 Basic Route

Here's a simple example of a route mapping:

# config/routes.rb

Rails.application.routes.draw do
  get 'welcome/home', to: 'welcome#home'
end

This maps a GET request to the URL /welcome/home to the home action in the WelcomeController.

3.2 Resource Routing

This is how you define routes for a resource:

# config/routes.rb

Rails.application.routes.draw do
  resources :articles
end

This will create seven different routes in your application, all mapping to the ArticlesController.

4. Summary

In this tutorial, we've covered the basics of Rails Routing, how to define routes, and routing best practices. As a next step, you could delve deeper into advanced routing concepts such as nested resources and routing constraints.

5. Practice Exercises

5.1 Exercise 1

Define a route that maps a GET request to the URL /about to the about action in the PagesController.

5.2 Exercise 2

Define resourceful routes for a BooksController.

5.3 Solutions

Here are the solutions for the exercises:

5.3.1 Solution for Exercise 1

# config/routes.rb

Rails.application.routes.draw do
  get 'about', to: 'pages#about'
end

5.3.2 Solution for Exercise 2

# config/routes.rb

Rails.application.routes.draw do
  resources :books
end

This will create seven different routes, all mapping to the BooksController.