如何让url_helper在Rails中传递permalink而不是id?

时间:2011-06-02 18:25:05

标签: ruby-on-rails ruby-on-rails-3 seo url-routing permalinks

我的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),但这看起来很脏。

我在路线上遗漏了什么?

谢谢!

2 个答案:

答案 0 :(得分:6)

在模型上定义一个to_param方法,返回您要使用的字符串。

class Post < ActiveRecord::Base
  def to_param
    permalink
  end
end

有关详细信息,请参阅this pagethis 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) %>

答案 1 :(得分:-1)

尝试这样的事情:

<%= link_to @post.title, post_path(:permalink => @post.permalink) %>

Rails应根据您的路线自动构建网址(即相应地替换:permalink)。