自定义路径生成器

时间:2012-05-12 18:55:58

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

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

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

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

但由于某些原因,当我尝试使用post_path(@post)时,在我的一个控制器中,它只返回完整的URL,例如/posts/4faddb375d9a1e045e000068/asdf(这是浏览器中的当前URL),而不是{ {1}}。

在我的路线档案中:

/posts/4faddb375d9a1e045e000068/post-title-here

奇怪的是,如果我使用get '/posts/:id/:slug' => 'posts#show', :as => 'post',它可以正常工作。如果在视图中我使用post_path(@post, @post.url)它可以正常工作。 (post_path(@post)返回网址友好标题)

如果您无法分辨,我正在尝试最终获得类似于stackoverflow的行为,其中url包含id和末尾的slug,如果slug与具有给定id的模型不匹配,它会重定向到正确的网址。

1 个答案:

答案 0 :(得分:0)

我要尝试的是将整个def post_path放在application_controller.rb中并使其成为helper_method :post_path的助手。你将获得两全其美的好处。

相关问题