Routing Helpers

Routing helpers are made of one public method (#routes), available for actions, views and templates. It's a factory to generate relative or absolute URLs, starting from named routes.

For a given route named :home, we can use home_path or home_url to generate relative or absolute URLs, respectively.

Usage

Imagine we have the following routes for our application:

# apps/web/config/routes.rb
root        to: 'home#index'
get '/foo', to: 'foo#index'

resources :books

Relative URLs

We can do:

<ul>
  <li><a href="<%= routes.root_path %>">Home</a></li>
  <li><a href="<%= routes.book_path %>">Books</a></li>
</ul>

Which generates:

<ul>
  <li><a href="/">Home</a></li>
  <li><a href="/books">Books</a></li>
</ul>

We can't link /foo, because it isn't a named route (it lacks of the :as option).

Absolute URLs

module Web::Controllers::Books
  class Create
    include Web::Action

    def call(params)
      # ...
      redirect_to routes.book_url(id: book.id)
    end
  end
end

In the case above, we have passed a Hash as set of params that are required to generate the URL.


Prev: Helpers - Forms
Next: Helpers - Assets
Looking for Lotus? We renamed the project and it's now called Hanami. Read the announcement.