Yuv*_*rmi 1 seo ruby-on-rails permalinks url-routing ruby-on-rails-3
我的Rails3项目中有以下路由:
match "/blog/:permalink" => "posts#show", :as => :post
当我通过视图链接到我的帖子时:
<%= link_to @post.title, post_path(@post) %>
帖子的id传递给post_path帮助器(即使我的路由指定了永久链接传递.
如何强制post_path发送永久链接而不是帖子的id?我可以明确地打电话,post_path(@post.permalink)但这看起来很脏.
我在路线上遗漏了什么吗?
谢谢!
to_param在模型上定义一个返回要使用的字符串的方法.
class Post < ActiveRecord::Base
  def to_param
    permalink
  end
end
有关详细信息,请参阅此页面,此Railscast(当然还有Google).
[编辑]
我不认为Polymorphic URL Helpers足够聪明,可以处理你想要做的事情.我认为你有两种选择.
1.使用特殊的命名路由并传入类似于您的问题和Jits的答案的参数.
match "/blog/:permalink" => "posts#show", :as => :post
并链接到它
<%= link_to @post.title, post_path(:permalink => @post.permalink) %>
2.创建一个为您生成URL的新助手
match "/blog/:permalink" => "posts#show", :as => :post_permalink
和帮助者
def permalink_to(post)
  post_permalink_path(post.permalink)
end
并在你的意见
<%= link_to @post.title, permalink_to(@post) %>
| 归档时间: | 
 | 
| 查看次数: | 2340 次 | 
| 最近记录: |