# Understanding the Rails Router: Why, What, and How

*Published on February 05, 2024*

---


Do you ever get the feeling that you know a topic is important and that you should know well, but you only understand it superficially? Ever since I got into Rails, I've had that feeling with&nbsp;[the Rails router](https://guides.rubyonrails.org/routing.html).

Transitioning from ASP.NET, I knew the concept of routing and got comfortable with the router after reading the docs. However, at the back of my mind, I've always had that nagging feeling that&nbsp;**I don't REALLY understand the complete picture**. I could make the basic routes and resources to get by for the simple CRUD tasks, but whenever I wanted to do something complicated, I found myself fumbling in dark.

Well, after over a year of fumbling and trying to skim the docs and StackOverflow to just learn enough to get by, I decided to dig deeper and&nbsp;_**REALLY**_&nbsp;understand how Routing works in Rails.

I've tried to summarize everything I learned in this one giant article. It's over 5,000 words, so don't expect to finish it in one sitting. However, if you can stick through it and read it till the end, I can pretty much guarantee that you'll have a much better understanding of how routing works in Rails. You'll also learn a few nice tips and tricks to clean up and simplify your existing routes right away.

Sounds interesting? Let's get started. Here's what we'll learn:

### What You'll Learn:

1. What is Routing?
2. Routing in Rails
3. Digging Deeper: Router Internals
4. A Short Detour: the&nbsp;`instance_exec`&nbsp;Method
5. The&nbsp;`match`&nbsp;Method and its Options
6. HTTP Method Shorthands
7. Understanding the Segment Keys
8. The Magic of Named Routes
9. Resourceful Routes
10. Non-Resourceful Custom Routes

We'll start with the basics, by understanding the purpose of routing in web applications and the role of the Rails router. Then we'll open the hood (i.e. the Rails codebase) and take a peek behind the scenes to understand how Rails implements the routing mechanism.

Then, we'll learn about the&nbsp;`match`&nbsp;method, which forms the core of most of the routing shorthand methods in Rails, such as&nbsp;`get`,&nbsp;`post`, etc. It leads us into covering a few fundamental routing topics such as segment keys and named routes.

Once we've learned the fundamentals, we'll be ready to tackle the practical routing topics, which you'll use day-to-day in your Rails apps. They include the concept of resources and RESTful routes, which drastically reduce the amount of code you write by following convention-over-configuration. We'll wrap up by learning the syntactic sugar provided by router to make it easy to create more expressive routes.

As it goes with all the posts on this blog, I'm writing to clarify my understanding and act as a reference for the future me, but I really hope that you, the reader, find my writing useful in gaining a deeper understanding of the router.

There's a little metaprogramming involved along the way, but don't worry, it's actually very simple to understand. If you need a quick primer on metaprogramming, check out my notes on the [Metaprogramming in Ruby](/metaprogramming-ruby) book.

Alright, enough talk. Let's get started. We've got a lot of ground to cover.

## What is Routing?

Before answering that, let me ask another question:&nbsp;**What happens when someone visits your application?**&nbsp;To keep things simple, let's ignore the load balancers, web servers, proxy servers, etc. and just assume the request hits your Rails application server.

**What happens when that request reaches your application?**

The very first thing that needs to happen is Rails needs to figure out which part of your codebase it should&nbsp;**send**&nbsp;**(or route)**&nbsp;that request to, so you can return a meaningful response to the browser. And here lies the answer to the question:&nbsp;_**What is Routing?**_

In simple terms,

> Routing is the process that determines what code in your application needs to run based on the URL of the incoming request.

Router is one of the first components to run when an HTTP request hits your application. It inspects the incoming URL and directs it to the appropriate Ruby code. Typically, this code will be an action method inside a Rails controller.

![router-flow.png](https://writesoftwarewell.com/media/g3o94p36j7706i1utpv6skxk2ke9.png "The Rails Router")

As you can see, the router is the first point of contact for a request inside your Rails application.

After inspecting the URL, the router decides to either:

1. forward the request to a controller action
2. redirect the request to another URL inside your application, or even to an external website or application
3. filter and reject the request based on pre-defined constraints or conditions, e.g. if the user is not logged in, then do not show the&nbsp;`/admin`&nbsp;page.

**If the router can't find a route that matches the incoming request, it throws an error.**

You can think of the router as a black box with a clear input and an output. Upon receiving the incoming HTTP request URL as an input, the router outputs the controller action where that request must be dispatched.

![url-to-action.png](https://writesoftwarewell.com/media/eru9pq1xt33934e47wpbz8hqj1pz.png "URL to Action")

However, the&nbsp;**router serves a dual purpose**&nbsp;in Rails. In addition to routing the incoming request to a controller action, it can also&nbsp;**dynamically generate the URLs for you**, so you don't need to hard-code string URLs throughout your app. Not only this approach is more maintainable, it also reads well and makes your codebase more expressive. We'll explore the named routes in&nbsp;[a later section](/understanding-rails-router-why-what-how#named-routes)&nbsp;of this post.

Now that you know what routing is, let's try to understand how routing works in the Rails framework.

## Routing in Rails

When you create a new Rails application, the application generator creates a&nbsp;`config/routes.rb`&nbsp;file which contains all the routes for your application. This gives a central place to look for all the paths and pages supported by your application.

To configure the router, you add specific rules (called&nbsp;_**routes**_) in the&nbsp;`routes.rb`&nbsp;file. These routes tell the router how to map incoming URLs to specific controller actions.

When a request on a specific URL endpoint arrives (e.g.&nbsp;`app.com/pages`), the router first finds the route which matches the URL pattern (`pages`). It does this by going through the routes in the order they're defined in the&nbsp;`routes.rb`&nbsp;file. As soon as it finds a matching route, the search ends. Each route has a corresponding&nbsp;`controller#action`&nbsp;method associated with it which gets called to generate the response HTML for that request.

The most basic way to define routes in Rails is to use the&nbsp;[`match`](https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-match)&nbsp;method. For example, the following route instructs Rails to direct any&nbsp;`POST`&nbsp;request with the URL&nbsp;`posts/publish`&nbsp;to the&nbsp;`publish`&nbsp;action method on the&nbsp;`PostsController`&nbsp;class.

```ruby
match "posts/publish/:id", controller: "posts", action: "publish", as: "publish", via: :post
```

> _Note: If you were expecting to see a shorthand route like_&nbsp;_`get posts/publish => posts#publish`__, I'm intentionally taking the difficult and longer route (no pun intended!) with the_&nbsp;_`match`_&nbsp;_method, as it will give you a deeper and better understanding of routing._

This single route contains multiple components that we'll examine in this post.

- the incoming URL&nbsp;`path`&nbsp;to match:&nbsp;`posts/publish`
- which controller and action this request should be routed to, i.e. the&nbsp;`publish`&nbsp;action on&nbsp;`PostsController`&nbsp;class
- the name for this route:&nbsp;`publish`, it generates URL helpers named&nbsp;`publish_url`&nbsp;and&nbsp;`publish_path`&nbsp;that you can use in your code.
- HTTP verb this route corresponds to&nbsp;`:post`
- segment key&nbsp;`:id`&nbsp;which acts as a variable placeholder for the ID of the post.

As you can see, the router offers a rich domain-specific language (DSL) to express a lot of information with a concise syntax. And&nbsp;**this is still a long-form version that you'll rarely use!!**

As you'll soon learn, Rails uses&nbsp;[convention-over-configuration](https://rubyonrails.org/doctrine#convention-over-configuration)&nbsp;to even shorten the above route without affecting its expressiveness.

For example, the above route could be simplified to:

```ruby
post "posts/publish/:id" => "posts#publish", as: "publish"
```

And it keeps getting better.

So that was a brief introduction to the routing process and the Rails router. Now let's inspect the internals of the router to understand what's going on behind the scenes. Trust me, this will be really useful as you learn more advanced features of the router later in the article.

## Digging Deeper: Router Internals

> In this section, we'll explore how Rails implements the beautiful routing DSL behind the scenes. This is going to be a bit technical, but nothing too complex.

Let's revisit the&nbsp;`config/routes.rb`&nbsp;file we saw earlier.

When you create a new Rails app, it automatically creates a&nbsp;`/routes.rb`&nbsp;file in the&nbsp;`config`&nbsp;directory. All it contains is a single call to the&nbsp;`draw`&nbsp;method on the object returned by the&nbsp;`Rails.application.routes`&nbsp;method. Additionally, it takes a block containing the routes for your application.

```ruby
Rails.application.routes.draw do
  # application routes go here...
end
```

To understand how the above method works, we need to take a short detour and understand Ruby's&nbsp;[`instance_exec`](https://ruby-doc.org/3.2.0/BasicObject.html#method-i-instance_exec)&nbsp;method defined on the&nbsp;[`BasicObject`](https://ruby-doc.org/3.2.0/BasicObject.html)&nbsp;class.

**Understanding How**&nbsp;**`instance_exec`**&nbsp;**Works**

The&nbsp;`instance_exec`&nbsp;method takes a block and runs that block in the context of the object on which it's called. Inside the block, it sets&nbsp;`self`&nbsp;to that object, so you can access its instance variables and methods.

```ruby
class Company
  def initialize(name, product)
    @name = name
    @product = product
  end

  def info
    "#{@name}: #{@product}"
  end
end

microsoft = Company.new 'Microsoft', 'Excel' 

microsoft.instance_exec do
  puts info    # access instance method
  puts @name   # access instance variable
end

# Output:

# Microsoft: Excel
# Microsoft
```

You might wonder what's the purpose of using&nbsp;`instance_exec`&nbsp;when you can just call the method directly on&nbsp;`microsoft`. You are, of course, right in this example, but, as we'll soon see, the most important benefit of&nbsp;`instance_exec`&nbsp;method is that&nbsp;**it allows you to pass a block and**&nbsp;_**run it later**_&nbsp;**in the context of an object.**&nbsp;This is really useful technique for creating special-purpose DSLs.

Not sure what I mean? let's revisit the&nbsp;`routes.rb`&nbsp;file.

```ruby
Rails.application.routes.draw do
end
```

The&nbsp;`Rails.application`&nbsp;is an instance of the&nbsp;`Application`&nbsp;class which inherits from the&nbsp;`Engine`&nbsp;class. The&nbsp;`Engine`&nbsp;class has a&nbsp;`routes`&nbsp;method which returns an instance of the&nbsp;`RouteSet`&nbsp;class.

```ruby
# railties/lib/rails/engine.rb

def routes(&block)
  @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config)

  # ...
  
  @routes
end
```

It means that the block passed to the&nbsp;`draw`&nbsp;method in the&nbsp;`routes.rb`&nbsp;file is ultimately received by the&nbsp;`draw`&nbsp;method on the&nbsp;`RouteSet`&nbsp;class. This method passes that block to the&nbsp;`eval_block`&nbsp;method, as seen below.

```ruby
# actionpack/lib/action_dispatch/routing/route_set.rb

def draw(&block)
  # ...
  eval_block(block)
  # ...
end

def eval_block(block)
  mapper = Mapper.new(self)
  
  mapper.instance_exec(&block)
end
```

As you can see, the&nbsp;`eval_block`&nbsp;method first creates an instance of the&nbsp;`ActionDispatch::Routing::Mapper`&nbsp;class and executes the block within the context of that instance.

What it means, is that&nbsp;**any code we write inside the block passed to the** **`Rails.application.routes.draw`**&nbsp;**method will be evaluated as if it was written inside the** **`Mapper`**&nbsp;**class.**

> 💡_If this is already started to get overwhelming and you feel like giving up,_ _**DON'T**__. Clone the Rails repo, open it in the editor, and trace the call stack with me. It's a fun exercise and you'll learn a lot along the way._

For example, the two pieces of code below are similar. However, the first version just reads better. It feels like&nbsp;**a programming language specifically designed for the routing domain.**

```ruby
Rails.application.routes.draw do
  root 'application#index'
  get 'posts/publish', to: 'posts#publish'
end

# is similar to 

routes = ActionDispatch::Routing::RouteSet.new
mapper = Mapper.new(routes)
mapper.root 'application#index'
mapper.get 'posts/publish', to: 'posts#publish'
```

This also means that whenever you see a method in your&nbsp;`routes`&nbsp;file, you know where to look for its definition. It's the&nbsp;`ActionDispatch::Routing::Mapper`&nbsp;class and its included modules. For example, the commonly used&nbsp;`get`&nbsp;method is defined in the&nbsp;`Mapper::HttpHelpers`&nbsp;module.

```ruby
def get(*args, &block)
  map_method(:get, args, &block)
end
```

This gives us a solid base to explore the Rails Routing API. We'll start our investigation with the&nbsp;`match`&nbsp;method.

## The match Method

> In this section, we will explore how the&nbsp;`match`&nbsp;method works behind the scenes.&nbsp;**Once you really understand the**&nbsp;**`match`**&nbsp;**method and its options, the rest of the routing methods and shorthands become very easy to understand.**

To understand the Rails Router API, it's essential to learn the&nbsp;[`match`](https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-match)&nbsp;method, which forms the core of the Router DSL. All helper methods like&nbsp;`get`&nbsp;and&nbsp;`post`&nbsp;use&nbsp;`match`&nbsp;under the hood. Additionally, most of the shorthand syntax such as&nbsp;`scopes`&nbsp;and&nbsp;`constraints`&nbsp;use the options provided by&nbsp;`match`&nbsp;behind the scenes.

Here's the basic API of the&nbsp;`match`&nbsp;method, which is defined inside the&nbsp;`Mapper`&nbsp;class.

```ruby
match(path, options)
```

The first parameter&nbsp;`path`&nbsp;tells the router what URL pattern you wish to match. It can be either a String or a Hash.

- The string version specifies the URL pattern, e.g.&nbsp;`/posts/publish/:id`
- The hash matches the URL pattern to a&nbsp;`controller#action`&nbsp;pair, like&nbsp;`'/posts/1' => 'posts#show'`.

The second parameter&nbsp;`options`&nbsp;is a hash containing additional data required by the router to decide where it should redirect this request. You can also pass any custom data, which gets passed to the&nbsp;`params`&nbsp;hash accessible in the controllers.

In its simplest and most explicit form, you supply a string URL pattern along with the name of the controller and the action via options.

```ruby
match 'photos/:id', controller: 'photos', action: 'show', via: :get
```

If you don't want to pass them separately, a string in the form of&nbsp;`controller#action`&nbsp;is also allowed with the&nbsp;`:to`&nbsp;option.

```ruby
match 'photos/:id', to: 'photos#show', via: :get
```

Finally, the hash version even simplifies this:

```javascript
match 'photos/:id' => 'photos#show', via: :get
```

As we'll learn later, you'll often use shortcuts like&nbsp;`get`&nbsp;and&nbsp;`post`&nbsp;instead of directly using the&nbsp;`match`&nbsp;method. However,&nbsp;`match`&nbsp;comes in handy when you want to match a route for multiple HTTP verbs.

```ruby
match 'photos/:id', to: 'photos#handle', via: [:get, :post]
```

Note: the&nbsp;`:via`&nbsp;option is mandatory for security-related reasons. If you don't pass it, the router raises an&nbsp;`ArgumentError`.

### Options Available to Match

The&nbsp;`options`&nbsp;hash helps the router identify the action to which it should pass the incoming request. Here are some of the important options that you can provide to the&nbsp;`match`&nbsp;method.

🤔 **Keep in mind:** Any custom data that doesn't match the existing option gets passed as-is to the&nbsp;`params`&nbsp;hash, which you can access in the controllers, using the&nbsp;`params`&nbsp;hash.

**`:controller`**&nbsp;and&nbsp;**`:action`**

The&nbsp;`controller`&nbsp;and&nbsp;`action`&nbsp;keys are used together. They specify the name of the controller and the action you want to route this request to.

```ruby
match 'home', controller: 'application', action: 'home', via: :get
```

**`:to`**

If you don't want to pass the controller and action separately, the&nbsp;`:to`&nbsp;option lets you pass the&nbsp;`controller#action`&nbsp;as a string.

```ruby
match 'home', to: 'application#home', via: :get
```

**Note:**&nbsp;You're not restricted to using only controller actions for incoming requests. The&nbsp;`:to`&nbsp;option also allows you to point to a Rack endpoint, i.e. any object that responds to a&nbsp;`call`&nbsp;method. This is really useful for quickly testing routes without creating new controllers, actions, and views.

```ruby
match 'path', to: -> (env) { [200, {}, ["Success!"]] }, via: :get
match 'path', to: RackApp, via: :get
```

If you're curious to learn more about Rack, check out this article: [The Definitive Guide to Rack for Rails Developers](/definitive-guide-to-rack)

**`via`**

Lists the HTTP verb for this route. You have to pass at least one HTTP verb, for security-related reasons.

```ruby
match 'path', to: 'controller#action', via: :get
match 'path', to: 'controller#action', via: [:get, :post]
match 'path', to: 'controller#action', via: :all
```

**`module`**

Use this if you want namespaced controllers. The following route directs the request with&nbsp;`/posts`&nbsp;URL to&nbsp;`Blog::PostsController#index`&nbsp;action.

```ruby
match '/posts', module: 'blog', controller: 'posts', action: 'index', via: :get
```

**`as`**

This option provides the name for the generated URL helpers. The following route creates the helpers named&nbsp;`blog_path`&nbsp;and&nbsp;`blog_url`.

```ruby
match 'posts', to: 'posts#index', as: 'blog', via: :get
```

**`constraints`**

If you want to put more restrictions on what URL patterns a route should match, provide this option with a hash of regular expressions. It can also take an object responding to&nbsp;`matches?`.

```ruby
match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }, via: :get
```

**`defaults`**

Sets the default value for a parameter. The following route will set the value of&nbsp;`params[:author]`&nbsp;to 'Akshay'.

```ruby
match '/courses/publish(/:author)', to: 'courses#publish', defaults: { author: 'Akshay' }, via: :get
```

For a complete list of options, check out&nbsp;[the API docs for the&nbsp;`match`&nbsp;method](https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Base.html#method-i-match). Most of the routing methods you'll use are just shorthands using various combinations of the&nbsp;`match`&nbsp;method's options.

Next, we'll learn about the shortcuts Rails provides, so you don't need to use the common options such as&nbsp;`:via`,&nbsp;`:module`, etc. all the time.

## HTTP Method Shorthands

So far, we've been using the&nbsp;`match`&nbsp;method, passing the HTTP verbs like&nbsp;`:get`&nbsp;and&nbsp;`:post`&nbsp;with the&nbsp;`:via`&nbsp;option. Can we do better? 🧐

**YES!**&nbsp;As you may already know, Rails provides simplified shorthand methods like&nbsp;`get`&nbsp;and&nbsp;`post`&nbsp;which implicitly assume the HTTP verb, inferred from the method name. For example, the following three routes mean the same thing.

```ruby
match 'posts', to: 'posts#index', via: :get

# ==

get 'posts', to: 'posts#index'

# OR

get 'posts' => 'posts#index'
```

There is a method for each HTTP verb.

- `get`
- `post`
- `patch`&nbsp;and&nbsp;`put`
- `delete`
- `options`

All of them accept the exact same options that we saw for the&nbsp;`match`&nbsp;method. For the remaining post, I'll use the above shorthands instead of the more explicit&nbsp;`match`&nbsp;method, unless needed.

Next, we'll learn another fundamental topic in routing,&nbsp;_**segment keys**_**.**

## Segment Keys

So far, we've seen route paths such as&nbsp;`posts/:id`. If you're new to routing, you might be wondering why there are symbols inside the URL. These symbol-like terms are called&nbsp;**segment keys, which make your URLs dynamic**.

Making a URL dynamic? What does that even mean? 🤔

It means that they allow the router to match both&nbsp;`posts/1`,&nbsp;`posts/2`&nbsp;and&nbsp;`posts/n`, where&nbsp;`n`&nbsp;can be anything.

> 💡A segment key is just a variable prefixed with a colon, just like a symbol, inside a URL pattern. It lets you capture the value inside the URL.

Instead of hard-coding a URL which matches exactly one URL, segment keys allow you to match more than one URL. You can access the values of those keys in the&nbsp;`params`&nbsp;hash, e.g.&nbsp;`params[:id]`.

Here's a segment key named&nbsp;`:slug`&nbsp;which lets you refer posts by their logical, dasherized name, i.e.&nbsp;`ruby-on-rails`.

```ruby
get '/posts/:slug', to: 'posts#show'
```

![slug.jpg](https://writesoftwarewell.com/media/zw8mi8otu4lyrst6iv8p7wj14xgl.jpg)

No, not this slug

> 💡A Slug is the unique identifying part of a web address.

When you make a GET request to the URL matching the above route, e.g.&nbsp;`/posts/understanding-router`, Rails sets&nbsp;`params[:slug]`&nbsp;to&nbsp;`understanding-router`. You can access the slug value inside the controller.

```ruby
class PostsController < ApplicationController
  def show
    @post = Post.find_by(slug: params[:slug])
  end
end
```

Note: If you use segment keys in a route, you have to provide their values when generating the URLs with the Rails helpers.

```ruby
<%= link_to 'Understanding Rails', controller: 'posts', action: 'show', slug: 'understanding-rails' %>
```

**But what if some of my URLs don't need a segment key?**

You can mark a segment key as optional by wrapping it in parentheses. The following route matches both&nbsp;`/posts/understanding-rails`&nbsp;and&nbsp;`posts`.

```ruby
get '/posts(/:slug)', to: 'posts#show'
```

**That's nice, but how can I restrict the slugs to only be text and not numbers?**

This is where the&nbsp;`constraints`&nbsp;option that we saw earlier, comes into the picture. You can add restrictions on the segment keys by providing a constraint.

The following route matches only those URLs where&nbsp;`slug`&nbsp;is a word consisting of letters between&nbsp;`a`&nbsp;to&nbsp;`z`.

```ruby
get '/posts/:slug', to: 'posts#show', constraints: { slug: /[a-z]+/ }

# or you can also use a shorthand
get '/posts/:slug', to: 'posts#show', slug: /[a-z]+/
```

**But I also want to access the request object...**

For more powerful constraints, you can pass a lambda to&nbsp;`:constraints`&nbsp;which receives the&nbsp;`request`&nbsp;object.

```ruby
get '/posts/:slug', to: 'posts#show', constraints: ->(req) { req.params[:slug].length < 10 }
```

**But, my constraint logic is too complicated, and I hate putting it right there inside the route...**

Rails allows you to extract the complex logic to a class that has a&nbsp;`matches(request)`&nbsp;method on it. Put that class inside the&nbsp;`app/constraints`&nbsp;directory, and Rails will pick it up without a hitch.

```ruby
get '/posts/:slug', to: 'posts#show', constraints: SlugLength.new

# app/constraints/slug_length.rb
class SlugLength
  def matches?(request)
    request.params[:slug].length < 5
  end
end
```

Don't forget to return a boolean result from the method, depending on whether the URL matches the pattern.

Alright, that's enough about the segment keys. Next, we'll tackle the named routes, which give you sweet helper methods to generate the URLs on the fly.

## Named Routes

So far, we have seen only one responsibility of the router: take an incoming HTTP request and route it to the piece of code (controller#action) that handles it.

- **Input:**&nbsp;HTTP Request URL
- **Output:**&nbsp;Controller and Action

![url-to-controller-action.png](https://writesoftwarewell.com/media/piyq0gxnzegdek43j52vjn3dj7pf.png "url-to-controller-action")

However, the Rails router works in the reverse way, as well. Given the route name (along with the corresponding data or model), the router can generate the resulting URL.

![controller-action-to-url.png](https://writesoftwarewell.com/media/ggetjqpaq9ovwlrdwwdinyx0cptg.png "controller-action-to-url")

Consider the following route.

```ruby
get 'post/:id', to: 'posts#show'
```

When you make a request to&nbsp;`post/10`, the router invokes the&nbsp;`show`&nbsp;action on the&nbsp;`PostsController`&nbsp;class.

What if you want to link to a post?&nbsp;**How would you go about creating the URL?**

Well, the simplest solution is to interpolate it, passing the post id.

```ruby
link_to post.title, "/post/#{post.id}"
```

But hard-coding URLs into your application is not always a good idea. When your URL changes, you'll have to search the whole codebase to find and replace the old URLs. If you miss one, your code won't complain until the users click the link, only to be shown an error page.

To fix this, you could provide the controller and action name along with the post id, so Rails could infer the URL.

```ruby
link_to post.title, controller: 'posts', action: 'show', id: post.id
```

However, there's an even better way with the&nbsp;**named routes,**&nbsp;where you can name a route by providing the&nbsp;`:as`&nbsp;option.

When you name a route, Rails will automatically generate helper methods to generate URLs for that route. These methods are called&nbsp;`name_url`&nbsp;or&nbsp;`name_path`, where&nbsp;`name`&nbsp;is the value you gave to the&nbsp;`:as`&nbsp;option.

Let's rewrite the above route and give it a name.

```ruby
match '/post/:id', to: 'posts#show', as: 'article'
```

The router creates two methods named:&nbsp;`article_path`&nbsp;and&nbsp;`article_url`. The difference between the two methods is that&nbsp;`article_path`&nbsp;returns only the path portion of the URL, whereas&nbsp;`article_url`&nbsp;returns the complete URL, which includes the protocol and domain.

```ruby
article_path(4) -> `/posts/4`
article_url(4)  -> `https://blog.com/posts/4` or `https://localhost:3000/posts/4`
```

Once you have named a route, you can use it as follows:

```ruby
link_to post.title, article_path(id: post.id)
```

It's less code to write, and it also avoids the problem of hard-coding the URL.

In fact, we can skip the&nbsp;`id`&nbsp;key, and just pass its value.

```ruby
link_to post.title, article_path(post.id)
```

We can go even further. Rails allows you to pass any object to the named helper methods as long as those objects have a&nbsp;`to_param`&nbsp;method on it.

```ruby
class Question
  def to_param
    '100'
  end
end

article_path(Question.new) # '/post/100'
```

What's more, all the active record objects have a&nbsp;`to_param`&nbsp;method out of box, which returns the object's&nbsp;`id`&nbsp;(you can customize this).

```ruby
link_to post.title, article_path(post)
```

This version is more readable, concise, and also avoids the problem of hard-coded URLs.

**Pretty cool, right?**

Now we're going to tackle one of the most practical concepts in routing that you'll use every day on your Rails apps:&nbsp;_**resources.**_

## Resourceful Routes

> 💡Resourceful routing allows you to quickly declare all of the common routes for a given resource. A single call to&nbsp;`resources`&nbsp;declares seven routes for&nbsp;`index`,&nbsp;`show`,&nbsp;`new`,&nbsp;`create`,&nbsp;`edit`,&nbsp;`update`, and&nbsp;`destroy`&nbsp;actions.

The concept of resources is very powerful in Rails. With a single call to a method named&nbsp;`resources`, Rails will generate seven different routes for you, saving you a lot of typing. But saving a few keystrokes is just the cherry on top. The biggest benefit of using resourceful routing is that it provides a nice organizational structure for your application. Let's learn how.

### **What's a Resource?**

A resource, like an object, is one of those concepts that's difficult to put into words. You intuitively understand them, but you can't express them.

I'll stick to how Roy Fielding, the inventor of REST, defined them in his&nbsp;[dissertation](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm).

> A resource&nbsp;_R_&nbsp;is a temporally varying membership function&nbsp;_M_R_(t)_, which for time&nbsp;_t_&nbsp;maps to a set of entities, or values, which are equivalent.

Is your head spinning? 🤯 Mine too. Let's try the other definition he gives in the same section.

> A resource is the key abstraction of information. Any information that can be named can be a resource.

Much better, right? 💡 I think that definition captures the essence of resources really well.

Any concept in your application domain can be a resource: an article, a course, or an image. It doesn't have to be a physical entity, but can be an abstract concept such as a weather forecast or an SSH connection to connect to a remote server.

The main point is:&nbsp;**you have total freedom**&nbsp;in choosing whatever idea you are using in your application as a resource.

**But Why do I need a Resource?**

Good question. You might be wondering what this discussion of resources has to do with routing. Well, resources are fundamental to routing. They allow you to&nbsp;**reduce seven different routes into a single method call.**

If you've used any software application, you must have noticed that most apps have a few common patterns. Most of the time, you're:

1. Creating some data (publishing a post, uploading an image)
2. Reading that data (viewing the tweets, listening to podcasts)
3. Updating the data (changing source code on GitHub, editing the post)
4. Deleting the data (removing a folder from Dropbox, deleting your profile picture)

No matter how fancy your application is, I guarantee it will have some form of these four actions that your users can take. Collectively, they're called&nbsp;**CRUD**&nbsp;which stands for&nbsp;_**Create, Read, Update**_**, and**&nbsp;_**Delete**_**.**

💡A resource is an object that you want users to be able to access via URI and perform [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete)&nbsp;operations.

For each of these actions, your application should have a route. Assuming you're building a course platform, your routes file might have the following routes.

```ruby
post   'courses'      => 'courses#create'
get    'course'       => 'course#show'
patch  'courses/:id'  => 'courses#update'
delete 'courses/:id'  => 'courses#destroy'
```

In addition to these four routes, you'll typically have three more:

- one to see all the courses
- two to fetch the pages that let the users create and modify the courses.

```ruby
get 'courses'          => 'courses#index'

get 'courses/new'      => 'courses#new'
get 'courses/:id/edit' => 'courses#edit'
```

So we have a total of seven routes that are common to most resources in most web applications. If you are building a blog, you'll have these seven routes for&nbsp;`posts`. If you're building Instagram, you'll have the same routes for&nbsp;`images`.

**No matter the topic, you'll most likely have some subset of these seven routes for each resource.**

Since this pattern is so common, Rails introduced the concept of resourceful routing, whereby calling one method named&nbsp;`resources`&nbsp;and passing the name of the resource, i.e.&nbsp;`:post`,&nbsp;`:course`,&nbsp;`:image`, etc. you get these seven routes for free. Rails will automatically generate them for you.

```ruby
Rails.application.routes.draw do
  resources :courses
end
```

In addition, resourceful routing also generates sensible names for these routes. For example, you'll have names like&nbsp;`course_path`,&nbsp;`edit_course_path`&nbsp;at your disposal without providing the&nbsp;`:as`&nbsp;option.

The following table summarizes what you get with a single call to&nbsp;`resources`. The values under the&nbsp;**Prefix**&nbsp;column represent the prefix of the route's name, e.g.&nbsp;`new_course`&nbsp;gives you&nbsp;`new_course_path`&nbsp;and&nbsp;`new_course_url`&nbsp;helpers, and so on.

```bash
➜ bin/rails routes -g course

     Prefix Verb   URI Pattern                 Controller#Action
    courses GET    /courses(.:format)          courses#index
            POST   /courses(.:format)          courses#create
 new_course GET    /courses/new(.:format)      courses#new
edit_course GET    /courses/:id/edit(.:format) courses#edit
     course GET    /courses/:id(.:format)      courses#show
            PATCH  /courses/:id(.:format)      courses#update
            PUT    /courses/:id(.:format)      courses#update
            DELETE /courses/:id(.:format)      courses#destroy
```

> Resourceful routing allows you to quickly declare all of the common routes for a given resource. A single call to&nbsp;`resources`&nbsp;declares seven routes for&nbsp;`index`,&nbsp;`show`,&nbsp;`new`,&nbsp;`create`,&nbsp;`edit`,&nbsp;`update`, and&nbsp;`destroy`&nbsp;actions.

In addition to having multiple resources, there's also a singular form of resourceful routes. It represents a resource that only has one, single form. For example, a logged-in user's profile. You can use the&nbsp;`resource`&nbsp;method for this.

```ruby
resource :profile
```

It creates the following routes:

```bash
 new_profile GET    /profile/new(.:format)  profiles#new
edit_profile GET    /profile/edit(.:format) profiles#edit
     profile GET    /profile(.:format)      profiles#show
             PATCH  /profile(.:format)      profiles#update
             PUT    /profile(.:format)      profiles#update
             DELETE /profile(.:format)      profiles#destroy
             POST   /profile(.:format)      profiles#create
```

Note two important differences from the plural version:

1. The route to show all profiles is missing. Since we only have a single profile, there's no point in displaying all.
2. None of the routes contain an&nbsp;`id`&nbsp;segment key. We don't need it to identify a profile as there's only one profile.

**What if I don't have all seven routes?**

Sometimes, you don't want all seven routes that&nbsp;`resources`&nbsp;method creates for you. In such cases, you can pass the&nbsp;`only`&nbsp;or&nbsp;`except`&nbsp;options to filter the ones you need or don't need.

```ruby
resources :courses, only: [:index, :show]

resources :courses, except: [:delete]
```

You can even nest multiple resources, but I'll leave that topic for a different post, since this one is already getting bigger than I anticipated.

## Non-Resourceful Custom Routes

A single call to&nbsp;`resources`&nbsp;in the&nbsp;`routes.rb`&nbsp;file declares the seven standard routes for your resource.&nbsp;**What if you need additional routes?**

Don't worry, Rails will let you create custom routes that don't fit one of the above seven routes with the&nbsp;`member`&nbsp;and&nbsp;`collection`&nbsp;routes. The&nbsp;`member`&nbsp;route only applies to a single resource, whereas&nbsp;`collection`&nbsp;will apply to a group of resources.

### **Member Routes**

Let's assume that your users need to see a preview of the course before purchasing it, and you need to expose that route on the&nbsp;`courses/:id/preview`&nbsp;URL. How should you go about it?

Here's how you define the&nbsp;`preview`&nbsp;route on the&nbsp;`CoursesController`&nbsp;using the&nbsp;`member`&nbsp;block.

```ruby
resources :courses do
  member do
    get 'preview'
  end
end
```

The router adds a new route that directs the request to the&nbsp;`preview`&nbsp;action on the `CoursesController`&nbsp;class. The remaining routes remain unchanged.

It also passes the course id in&nbsp;`params[:id]`&nbsp;and creates the `preview_course_path` and and&nbsp;`preview_course_url`&nbsp;helpers.

```bash
preview_course GET    /courses/:id/preview(.:format) courses#preview
```

If you have a single&nbsp;`member`&nbsp;route, use the short-hand version by passing the&nbsp;`:on`&nbsp;option to the route, eliminating the block.

```ruby
resources :courses do
  get 'preview', on: :member
end
```

Although this approach works fine, a better way is to create a new controller dedicated to previewing images. Typically, you should strive to restrict your controllers with the seven default actions.

> What I’ve come to embrace is that being almost fundamentalistic about when I create a new controller to stay adherent to REST has served me better every single time. Every single time I’ve regretted the state of my controllers, it’s been because I’ve had too few of them. I’ve been trying to overload things too heavily.  
>   
> \- DHH, on&nbsp;[Full Stack Radio](http://www.fullstackradio.com/32)

### **Collection Routes**

Let's say you want to search all courses and you want to expose it on the&nbsp;`courses/search`&nbsp;endpoint. You can add a new route for the collection of courses with the&nbsp;`collection`&nbsp;block.

```ruby
resources :courses do
  collection do
    get 'search'
  end
end
```

This adds the following new route. It will also add a&nbsp;`search_courses_path`&nbsp;and&nbsp;`search_courses_url`&nbsp;helpers.

```bash
search_courses GET    /courses/search(.:format)   courses#search
```

If you don't need multiple&nbsp;`collection`&nbsp;routes, just pass&nbsp;`:on`&nbsp;option to the route.

```ruby
resources :courses do
  get 'search', on: :collection
end
```

This will add the same route as above.

To learn more about custom routes, check out this article: [Define New Routes Using the Member and Collection Blocks](/define-new-routes-using-member-and-collection-blocks-in-rails)

As we saw, the Rails router is very powerful and highly flexible. Routing is also a two-way street:&nbsp;**match URLs to controller actions, and generate URLs dynamically.**&nbsp;Additionally, the router uses powerful conventions such as resourceful routing to automatically generate sensible routes for you.

Alright, I will stop here. There are a few other shortcuts and helper methods that we didn't cover in this article, but I've already written more than 5000 words non-stop, and this article is way, wayy, wayyy bigger than what I first thought it would be. If you're still reading, I sincerely hope that you learned at least one new thing about the Rails router that you didn't know before.

Expect a few posts in the upcoming weeks that will explain the remaining topics. But what we've covered so far should be more than enough for you to get started and be productive with using various routing features, both basic and advanced, in your applications.

Here're some additional resources, if you want to learn more about routing.

### Further Resources

- [Rails Routing from the Outside In](https://guides.rubyonrails.org/routing.html)
- [Rails API: The Mapper Class](https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper.html)
- [Routing in Laravel](https://laravel.com/docs/10.x/routing)&nbsp;(to learn routing from a different framework's perspective)
- [Roy Fielding's Dissertation](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm)

