如何在 Rails 应用程序中使用 link_to 将文章标题添加到 URL? [英] How to add article title to URL using link_to in Rails app?

查看:43
本文介绍了如何在 Rails 应用程序中使用 link_to 将文章标题添加到 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试关注 回答 问题

I am trying to follow answer to question

如何获取link_toRails 输出一个 SEO 友好的 url?

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

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

然而,重启服务器后,链接没有标题:/articles/1、/articles/2

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

怎么了?

推荐答案

您的 link_to 将使用来自 resources :articles 的路由.如果您希望它使用您定义的自定义路由,请命名该路由,然后在您的 link_to 中使用它:

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)

此外,您可能需要考虑使用 friendly_id.它为您执行此操作,但更透明.

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

这篇关于如何在 Rails 应用程序中使用 link_to 将文章标题添加到 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆