"posts#show", :as => :post 当我通过这样的 View 链接到我的帖子时: 帖-6ren">
gpt4 book ai didi

ruby-on-rails - 如何让 url_helper 在 Rails 中传递永久链接而不是 id?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:32:40 24 4
gpt4 key购买 nike

我的 Rails3 项目中有以下路线:

match "/blog/:permalink" => "posts#show", :as => :post

当我通过这样的 View 链接到我的帖子时:

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

帖子的 ID 被传递到 post_path 助手(即使我的路由指定传递永久链接。

我如何强制 post_path 发送永久链接而不是帖子的 ID?我可以显式调用 post_path(@post.permalink) 但这看起来很脏。

我是不是在我的 route 遗漏了什么?

谢谢!

最佳答案

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

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

参见 this page , this 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

还有一个 helper

def permalink_to(post)
post_permalink_path(post.permalink)
end

在你看来

<%= link_to @post.title, permalink_to(@post) %>

关于ruby-on-rails - 如何让 url_helper 在 Rails 中传递永久链接而不是 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com