Reputation: 14275
Learning ruby on rails, playing around with routes and path methods. I have built a fairly simple application with the models "Book" and "Author". Each author can have many books, every book belongs to an author, etc.
I have an authors controller with the method #list that lists all authors. When it does that, it also echoes out all their books. Now I would like each book to point to books#show with this nifty path method I found.
Here is my snippet:
<% @authors.each do |author| %>
<li><%= author.name %></li>
<ul>
<% author.books.all.each do |book| %>
<li><%= link_to book.name, controller: :books, action: :show, id: book.id %></li>
<% end %>
</ul>
<% end %>
With this link_to book.name, controller: :books, action: :show, id: book.id
it works fine, but something tells me the same can be achieved much easier. If I use books_show_path(book)
it won't work.
My routes look like the following:
root to: 'authors#list'
match 'authors/list' => 'authors#list'
match 'books/list' => 'books#list'
match 'authors/:id/delete' => 'authors#delete'
match 'authors/:id/show' => 'authors#show'
match 'books/:id/show' => 'books#show'
What am I doing wrong here? What do I need to do to make books_show_path(book)
work?
Upvotes: 1
Views: 2546
Reputation: 20639
Check out Resource Routing section of Rails Guides.
In short, the convention is that you define resources :books
in routes, that will route /books to index action and /books/123 to show action etc. You will also have some helper methods to generate the path:
book_path(book) #=> /books/123
books_path #=> /books
In fact, link_to and a bunch of other methods can generate path from object itself:
link_to book.name, book # will also call book_path(book) under the hood
Upvotes: 3
Reputation: 5437
as
option is for route name
match 'books/:id/show' => 'books#show', as: :books_show
But i strongly recommend you to read about resource routing
Upvotes: 2