This tutorial aims to guide you through the process of defining custom and named routes in Rails. We'll explore how to create routes that do not strictly follow the usual RESTful conventions and how to name your routes for clearer and more meaningful code.
By the end of this tutorial, you'll learn:
- How to define custom routes in Rails
- How to name your routes in Rails
Prerequisites:
- Basic understanding of Ruby on Rails
- Ruby on Rails installed on your local machine
In Rails, routes are defined in the config/routes.rb
file. Rails provides a domain-specific language (DSL) for defining routes.
To define a custom route, you can use the match
method. It allows you to match a URL to a corresponding controller action.
For named routes, Rails provides the as
option. This allows you to create a named route that generates helper methods.
Example 1: Defining a Custom Route
# config/routes.rb
Rails.application.routes.draw do
match '/register' => 'users#new', via: :get
end
In this example, '/register'
is the path in the URL, 'users#new'
is the controller and action, and via: :get
specifies the HTTP method.
Example 2: Defining a Named Route
# config/routes.rb
Rails.application.routes.draw do
get '/register' => 'users#new', as: 'register'
end
In this example, as: 'register'
names the route 'register'. This generates register_path
and register_url
helper methods which return '/register'.
In this tutorial, we learned:
- How to define custom routes in Rails using the match
method
- How to define named routes in Rails using the as
option
To continue learning, explore more complex routing patterns and nested resources.
Additional resources:
- Rails Routing
- Rails Routing from the Outside In
Exercise 1: Define a custom route for a login page. The route should point to a sessions#new
action and should be accessible via a GET request.
Solution:
# config/routes.rb
Rails.application.routes.draw do
match '/login' => 'sessions#new', via: :get
end
Exercise 2: Define a named route for the login page you created above. Name the route 'login'.
Solution:
# config/routes.rb
Rails.application.routes.draw do
get '/login' => 'sessions#new', as: 'login'
end
These exercises should help solidify your understanding of custom and named routes in Rails. Continue practicing with different controller actions and HTTP methods.