【问题标题】:Custom path generator自定义路径生成器
【发布时间】:2012-05-20 22:41:20
【问题描述】:

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

我尝试在我的 ApplicationHelper 中添加类似的内容:

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

但由于某种原因,在我的一个控制器中,当我尝试使用 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),它可以正常工作。如果在视图中我使用post_path(@post) 它可以正常工作。 (@post.url 返回 url 友好标题)

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

【问题讨论】:

  • 你在哪里定义'post.url'?
  • post.url 是模型上的一个方法,并以 url 友好的方式返回帖子的标题。

标签: ruby-on-rails ruby url routes helper


【解决方案1】:

我会尝试将整个def post_path 放入application_controller.rb 并使其成为helper_method :post_path 的助手。您将两全其美。

【讨论】:

  • 很高兴看到将路径直接注入Rails.application.routes.url_helpers的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多