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.