想象一下posts
和comments
的博客。个人评论的网址可能是posts/741/comments/1220
。
但是,我想建立网址posts/741#1220
,甚至是posts/741#comment-1230
。
这样做最不具侵扰性的方法是什么,以便redirect_to comment_path(my_comment)
指向正确的网址?
答案 0 :(得分:61)
你可以简单地使用
redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}")
使用锚点手动构建URL。这样,您仍然可以在路线中将评论的绝对网址设为posts/:post_id/comments/:comment_id
。您还可以在例如创建辅助方法。 application_controller.rb
class ApplicationController
helper :comment_link
def comment_link(comment)
post_path(comment.post, :anchor => "comment-#{comment.id}")
end
end
答案 1 :(得分:0)
希望将您的锚点生成器保留在一个位置。
class Comment
...
def anchor
"comment-#{id}#{created_at.to_i}"
end
end
然后
post_path(comment.post, :anchor => comment.anchor)
添加created_at.to_i
会使您的数据更加模糊,并且不会对任何事情造成任何伤害。
答案 2 :(得分:-2)
你可以在评论中覆盖方法to_param来做到这一点。
例如
def to_param
comment.post_id.to_s + '#' + id.to_s
end
你必须调整routes.rb。有关详细信息,请查看此blog。