How do you use anchors for IDs in routes in Rails 3?

时光毁灭记忆、已成空白 提交于 2019-11-29 16:39:46

问题


Imagine a blog with posts and comments. An individual comment's URL might be posts/741/comments/1220.

However, I'd like to make the URL posts/741#1220, or even posts/741#comment-1230.

What's the least intrusive way of doing this, so that redirect_to comment_path(my_comment) points to the correct URL?


回答1:


You could simply use

redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}")

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



回答2:


Prefer to keep your anchor builder in one place.

class Comment
  ...
  def anchor
    "comment-#{id}#{created_at.to_i}"
  end
end

then

post_path(comment.post, :anchor => comment.anchor)

Adding the created_at.to_i obscures your data a bit more and doesn't harm anything.




回答3:


you could override the method to_param in comment to do that.

for example

def to_param
  comment.post_id.to_s + '#' + id.to_s
end

And you'll have to tweak routes.rb. Check this blog for more information.



来源:https://stackoverflow.com/questions/4981029/how-do-you-use-anchors-for-ids-in-routes-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!