4

I am trying to follow answer to question

How to get link_to in Rails output an SEO friendly url?

but don't get the result. In my Rails 3 app I have:

# routes.rb
match '/articles/:id/:title' => 'articles#show'
resources :articles

# articles/index.html.haml
- @articles.each do |article|
  = link_to article.title, article, :title => article.title

However, after restarting the server, the links don't have the title: /articles/1, /articles/2

What is wrong?

Community
  • 1
  • 1
Andrei
  • 10,918
  • 12
  • 76
  • 110

1 Answers1

7

Your link_to will be using the route from resources :articles. If you want it to use the custom route you've defined, name the route, and then use that in your link_to:

# routes.rb
match '/articles/:id/:title' => 'articles#show', :as => :article_with_title

# articles/index.html.erb
link_to article.title, article_with_title_path(article, :title => article.title)

Also, you may want to consider looking into using friendly_id. It does this for you, but more transparently.

idlefingers
  • 31,659
  • 5
  • 82
  • 68
  • 1
    I removed my answer which was incomplete and editing it would duplicate yours. I will mention that friendly_id is awesome but a different solution to that posted. – mark Jan 25 '11 at 14:10
  • thanks! `friendly_id` is more than I need. May be you know how one can make an universal helper for handling various routes `/articles/:id/:title`, `/users/:id/:name` etc., i.e. similar to SO routes? – Andrei Jan 25 '11 at 17:04
  • Have you tried searching for that? There's a bunch of very similar questions on SO - http://stackoverflow.com/questions/4434266 for one.. – idlefingers Jan 25 '11 at 17:12
  • all of them suggest `friendly_id` which works with `/articles/:title` and is unnecessary in my case, since I already have `id` in the routes. The problem is that I don't know how to make an universal logic for my models appending the extra part to the routes. – Andrei Jan 26 '11 at 14:42
  • Just want to add that you'll probably want to add the `routes.rb` line suggested AFTER you state `resources :articles` otherwise you might have an issue with your edit links routing to show page. – veritas1 Nov 01 '12 at 13:54