gpt4 book ai didi

ruby-on-rails - 自定义路径生成器

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:39 24 4
gpt4 key购买 nike

我以为我知道如何覆盖路径助手,但我没有得到预期的行为。

我尝试将类似这样的内容添加到我的 ApplicationHelper 中:

def post_path(post)
"/posts/#{post.id}/#{post.url}"
end

但出于某种原因,在我的一个 Controller 中,当我尝试使用 post_path(@post) 时,它只返回完整的 url,例如 /posts/4faddb375d9a1e045e000068/asdf(这是浏览器中的当前 url)而不是 /posts/4faddb375d9a1e045e000068/post-title-here

在我的路线文件中:

get '/posts/:id/:slug' => 'posts#show', :as => 'post'

奇怪的是,如果我使用 post_path(@post, @post.url),它会正常工作。如果在 View 中我使用 post_path(@post) 它可以正常工作。 (@post.url 返回 url 友好标题)

万一你不知道,我试图最终得到类似于 stackoverflow 的行为,其中 url 包含 id 和末尾的 slug,如果 slug 与给定 id 的模型不匹配,它将重定向到正确的 url。

最佳答案

我会尝试将整个 def post_path 放在 application_controller.rb 中,并使用 helper_method :post_path 使其成为一个助手>。您将两全其美。

关于ruby-on-rails - 自定义路径生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10566524/

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