在Rails 3中如何在ID中使用锚作为ID? [英] How do you use anchors for IDs in routes in Rails 3?

查看:74
本文介绍了在Rails 3中如何在ID中使用锚作为ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一个博客,其中有个帖子个评论。单个评论的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中使用锚作为ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆