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

我想回答问题的答案

如何在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 

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

怎么了?

您的link_to将使用来自resources :articles的路线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) 

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