# Understanding the Match Method in Rails Router

*Published on July 15, 2024*

Tags: Router

---


> This post is part of my&nbsp;[handbook on the Rails Router](/tag/router).

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.

In its essence, the&nbsp;`match`&nbsp;method matches a URL pattern to one or more routes. Here's the basic API of the&nbsp;`match`&nbsp;method, which is defined inside the&nbsp;`Mapper`&nbsp;class.

```ruby
# actionpack/lib/action_dispatch/routing/mapper.rb
def match(path, options = nil)
end
```

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.

Here are some usage examples of the&nbsp;`match`&nbsp;method.

```ruby
match 'photos/:id' => 'photos#show', via: :get
match 'photos/:id', to: 'photos#show', via: :get
match 'photos/:id', controller: 'photos', action: 'show', via: :get
```

All the three routes above do the same thing, dispatch the HTTP GET request at&nbsp;`/photos/:id`&nbsp;to the&nbsp;`show`&nbsp;action method on the&nbsp;`PhotosController`&nbsp;class.

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 simplifies this even further:

```ruby
match "photos/:id" => "photos#show", via: :get
```

**Matching Multiple HTTP Verbs**

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 Method

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
```

To learn more about forwarding a request to a Rack application, check out the following post: [How to Route an Incoming URL to a Rack Application in Rails](/route-to-rack-app-endpoint-rails)

**`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
```

Alternatively, you can use the shorthand helper methods such as&nbsp;`get`,&nbsp;`post`, and so on which implicitly provide the HTTP verb.

**`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
```

To learn more about named routes, check out the following post: [Understanding Named Routes in Ruby on Rails](/understanding-named-routes-in-rails)

**`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.

`param`

In the resourceful routes,&nbsp;`:id`&nbsp;is the name of the dynamic segment used to generate the routes. The&nbsp;`param`&nbsp;option overrides this default resource identifier. You can access the value of this dynamic segment using&nbsp;`param[<:param>]`.

```ruby
resources :posts, param: :slug
```

The&nbsp;`posts`&nbsp;resource will contain&nbsp;`:slug`&nbsp;as the dynamic segment, e.g.&nbsp;`posts/:slug`.

To construct the URL, override the&nbsp;`ActiveRecord::Base#to_param`&nbsp;method.

```ruby
class Post < ApplicationRecord
  def to_param
    title.parameterize
  end
end

post = Post.find_by(title: "Ruby on Rails")
post_path(post)  # "/posts/ruby-on-rails"
```

