0

Here are the routes I've written:

Foo::Application.routes.draw do
  get "home/index"

  match "/ads/:category_name" => "ads#by_category"
  match "/ads/:category_name/:id" => "ads#show"

  resources :ads

  root :to => 'home#index'
end

In one of my shared views, I wrote a sidebar element that displays all categories:

<div id="category-sidebar">
  <h2>Categorias</h2>
  <% Category.order('name').each do |category| %>
    <%= link_to category.name %>
  <% end %>
</div>

This generates:

<div id="category-sidebar">
  <h2>Categorias</h2>
    <a href="/ads/Aeronautica">Aeronautica</a>
    <a href="/ads/Aeronautica">Agropecuaria y Campo</a>
    <a href="/ads/Aeronautica">Alimentos y Bebidas</a>
    <a href="/ads/Aeronautica">Animales y Mascotas</a>
    <a href="/ads/Aeronautica">Arte y Antiguedades</a>
</div>

I'd like to generate an href like:

/ads/Aeronautica
/ads/Alimentos%20y%20Bebidas

What am I missing here?

sergserg
  • 21,716
  • 41
  • 129
  • 182

1 Answers1

1

Use bundle exec rake routes to find the named route for your "/ads/:category_name/:id" path. Let's say that this route is called 'categories'. You can then do (note the '_path' bit):

Category.order('name').each do |category|
  link_to category.name, categories_path(:id => category.id)
end
Reck
  • 7,966
  • 2
  • 20
  • 24
  • Great tip, thank you! How can I give the path a name in `routes.rb`? – sergserg Feb 02 '13 at 22:22
  • If you're not happy with the names rails generates by default, you can explicitly name a route like this: http://stackoverflow.com/questions/7913682/how-to-name-a-route-in-rails – Reck Feb 02 '13 at 22:28