问题描述
想象一个包含 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!