如何在Rails应用程序中使用link_to将文章标题添加到URL?

And*_*rei 4 seo ruby-on-rails link-to ruby-on-rails-3

我想回答问题的答案

如何在Rails中获取link_to输出一个SEO友好的URL?

但是没有得到结果.在我的Rails 3应用程序中,我有:

# 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
Run Code Online (Sandbox Code Playgroud)

但是,重新启动服务器后,链接没有标题:/ articles/1,/ articles/2

怎么了?

idl*_*ers 7

link_to将使用该路线resources :articles.如果您希望它使用您定义的自定义路由,请为该路由命名,然后在以下位置使用该路由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)
Run Code Online (Sandbox Code Playgroud)

此外,您可能需要考虑使用friendly_id.它为你做到了这一点,但更透明.