Skip to the workspace
Pebellslearn by building
Routing Fundamentals  ›  Lesson

Named Routes and Inspecting Routes

Named Routes 12 minEach route gets a name that becomes _path and _url helpers, and bin/rails routes lists every route with its name, method, path and action.

ruby on rails / Named Routes and Inspecting Routes

Explore each scene at your own pace.

01 · The rule

The rule

Named Routes and Inspecting Routes

Hard-coding "/books/7/edit" into a view works until someone renames a URL, and then dozens of links break quietly. Rails avoids this by naming routes and generating methods that build their URLs for you. The same names show up when you ask Rails to list its routes.

The rule

Name the route, call the helper, never type the URL.

Every route from resources :books has a name. Add _path for a relative path or _url for a full URL:

Helper Gives
books_path /books
new_book_path /books/new
book_path(@book) /books/7
edit_book_path(@book) /books/7/edit

Pass a record and Rails uses its id. The same book_path(@book) serves show, update and destroy, because they share a path and differ only by method.

<%= link_to "All books", books_path %>
<%= link_to @book.title, book_path(@book) %>
<%= link_to "Edit", edit_book_path(@book) %>

You can name a hand-written route with as::

get "about", to: "pages#about", as: :about   # about_path

To see everything, run:

bin/rails routes              # every route
bin/rails routes -g review    # only lines matching "review"
bin/rails routes -c books     # only BooksController
   Prefix Verb   URI Pattern               Controller#Action
    books GET    /books(.:format)          books#index
edit_book GET    /books/:id/edit(.:format) books#edit
     book GET    /books/:id(.:format)      books#show

The Prefix column is the helper name without _path. A blank prefix means the line shares the name above it. In development you can also visit /rails/info/routes in the browser.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.