How to add article title to URL using link_to in R

2019-02-10 14:27发布

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?

1条回答
【Aperson】
2楼-- · 2019-02-10 14:48

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.

查看更多
登录 后发表回答