# Understanding Named Routes in Rails

*Published on July 10, 2024*

Tags: Router

---


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

So far, we've learned how the Rails router matches the incoming URL to a route defined in the&nbsp;`routes.rb`&nbsp;file and dispatches that request to the corresponding action method on a controller class.

![router-flow.png](https://writesoftwarewell.com/media/mcdfezwqynf51wr8uu4rrwc00v67.png)

However, the Rails router also works in the other way. That is, given the controller and action, it can generate the URL for that route. You can also name a route and use it to generate the matching URL.

### How to Name a Route in Rails?

You can name a route by passing the&nbsp;`:as`&nbsp;option. Naming a route creates two methods in your Rails application. The method names follow the convention of&nbsp;`{name}_path`&nbsp;and&nbsp;`{name}_url`, where&nbsp;`name`&nbsp;is the name of the route.

For example, consider the following route.

```ruby
get "/account", to: "pages#account", as: "user_account"
```

Rails will automatically generate the methods&nbsp;`user_account_path`&nbsp;and&nbsp;`user_account_url`.

**What's the difference between**&nbsp;**`_path`**&nbsp;**and**&nbsp;**`_url`****?**

- Calling&nbsp;`user_account_path`&nbsp;method generates only the path component of the URL:&nbsp;`/account`
- Calling&nbsp;`user_account_url`&nbsp;method generates the entire URL, including host and protocol:&nbsp;`http://www.example.com/account`.

You can use these helper methods in any place where you need a URL or a path, for example, the helpers such as&nbsp;`link_to`&nbsp;or&nbsp;`button_to`:

```ruby
link_to user_account_path
```

### **How to Access URL Helper Methods in Rails?**

You can use the helper methods directly in the views as well as the integration tests.

```ruby
button_to user_account_path
```

However, if you want to access them in the controller, you've to use the&nbsp;`helpers`&nbsp;method, which returns an instance of the view.

```ruby
class PagesController < ApplicationController
  def profile
    helpers.user_account_url
    # ...
  end
end
```

Additionally, you can access the helper methods in the Rails console using the&nbsp;`app`&nbsp;object available in the console.

```bash
>> app.root_path
"/"
```

If the route expects any dynamic segments, you have to pass them via a hash to the named methods. Consider the following route:

```ruby
get "/portal/:product", to: "pages#portal", as: "portal"
```

To generate the URL corresponding to this route, you'll pass the product value as follows:

```ruby
portal_url(product: "ipad")    # "http://www.example.com/portal/ipad", 
portal_path(product: "iphone") # "/portal/iphone", 
```

