# How to Access Route Helpers from Rails Console and Models

*Published on April 19, 2022*

---


In Rails, routes map an incoming URL to a controller action. When you define a route for your application, you also get path and URL helpers to build relative or absolute URLs from the route’s name. For example, suppose that you have a&nbsp;`users`&nbsp;resource in your&nbsp;`config/routes.rb`:

```ruby
resources :posts
```

This route creates the method&nbsp;`posts_path`&nbsp;that you can use in the view. For simple routes, you can probably guess the output of the helper, e.g., the&nbsp;`posts_path`&nbsp;helper will return the URL&nbsp;`/posts`. For complex routes, especially nested ones, it can be hard to figure out the URL until you use the helper to render the view.

This post shows a simple way to check the output of URL and path helpers directly from the Rails console. We will also see how to access these helpers in your models.

Here’s a typical route file with a single route.

```ruby
# routes.rb

Rails.application.routes.draw do
  get '/posts/:id/preview', to: 'posts#preview', as: "preview_post"
end
```

This route maps the URL&nbsp;`posts/:id/preview`&nbsp;to&nbsp;`PostsController#preview`&nbsp;action. Additionally, we have named the route&nbsp;`preview_post`&nbsp;using the&nbsp;`as`&nbsp;option. Hence, Rails will automatically generate&nbsp;`preview_post_path`&nbsp;and&nbsp;`preview_post_url`&nbsp;helpers for us.

To see the routes in your application, you can run the&nbsp;`rails routes`&nbsp;command.

```ruby
> bin/rails routes -g preview

Prefix Verb URI     Pattern                  Controller#Action
preview_post GET  /posts/:id/preview(.:format) posts#preview
```

However, this doesn’t tell you what URL the route will generate for you. For that, you can call the helper methods on the&nbsp;`app`&nbsp;object, which represents your application. Rails adds all the helpers to the&nbsp;`app`&nbsp;object when it boots. Hence you can check the output of any named route helper in the console, which is pretty handy during development.

```ruby
irb(main):018:0> post = Post.first

irb(main):019:0> app.preview_post_path(post)
=> "/posts/5/preview"
```

## How to Access Route Helpers from Rails Models

By default, the helper methods are accessible from your controllers, views, and mailers. If you need to access the auto-generated helper methods from other places (such as a model), then you can do that by including&nbsp;`Rails.application.routes.url_helpers`&nbsp;in your class:

```ruby
class Post < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  def link
    post_path(self)
  end
end

Post.find(1).link # => "/posts/1"
```

