How to add article title to URL using link_to in Rails app?

I am trying to answer the question

How to get link_to in Rails to output a friendly SEO URL?

but do not get the result. In my Rails 3 application, 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 the server is restarted, the links are not named: / articles / 1, / articles / 2

What's wrong?

+4
source share
1 answer

Your link_to will use the route from resources :articles . If you want it to use the custom route that you defined, name the route and then use it in 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) 

Alternatively, you might consider using friendly_id . He does it for you, but more transparently.

+7
source

Source: https://habr.com/ru/post/1336978/


All Articles