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_pathTo 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#showThe 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.
The shortcut
When you need a link, run bin/rails routes -g <noun>, read the Prefix, add _path, pass the record if the pattern has :id.
Look it up
bin/rails routes -g bookshowsedit_book GET /books/:id/edit.
Use _url only where a full address is needed, such as in emails and redirects to another host.
Drills
Answer fast — trust the rule.
Which helper builds /books/new?
What does book_path(@book) return when @book.id is 5?
Which command lists only the routes handled by BooksController?
You add get "faq", to: "pages#faq", as: :help. Which helper exists now?
Remember
- Name the route, call the helper, never type the URL.
- Shortcut: routes -g, read Prefix, add _path, pass the record for :id.
- Trap: hard-coded URL strings that break silently when routes change.
