问题描述
想象一个包含 posts
和 comments
的博客.单个评论的 URL 可能是 posts/741/comments/1220
.
Imagine a blog with posts
and comments
. An individual comment's URL might be posts/741/comments/1220
.
但是,我想让 URL posts/741#1220
,甚至 posts/741#comment-1230
.
However, I'd like to make the URL posts/741#1220
, or even posts/741#comment-1230
.
这样做的侵入性最小的方法是什么,以便 redirect_to comment_path(my_comment)
指向正确的 URL?
What's the least intrusive way of doing this, so that redirect_to comment_path(my_comment)
points to the correct URL?
推荐答案
你可以简单地使用
redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}")
手动构建带有锚点的 URL.这样,您仍然可以在路由中将评论的绝对 URL 设为 posts/:post_id/comments/:comment_id
.您还可以创建一个辅助方法,例如application_controller.rb
to manually build the URL with the anchor. That way, you can still have the absolute URL to your comments as posts/:post_id/comments/:comment_id
in your routes. You can also create a helper method in e.g. application_controller.rb
class ApplicationController
helper :comment_link
def comment_link(comment)
post_path(comment.post, :anchor => "comment-#{comment.id}")
end
end
这篇关于您如何在 Rails 3 的路由中使用锚点作为 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!