36

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?

ClosureCowboy
  • 20,825
  • 13
  • 57
  • 71

2 Answers2

69

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
Holger Just
  • 52,918
  • 14
  • 115
  • 123
  • What would the benefit be of having my absolute URL still be posts/:post_id/comments/:comment_id? – ClosureCowboy Feb 13 '11 at 10:46
  • @ClosureCowboy: You could still properly define the comments as resources, to e.g. delete or edit them. It depends on your actual requirements if this makes sense to have or not. – Holger Just Feb 13 '11 at 11:27
  • Is the controller really the best place to put this kind of helper? I'm pondering this issue myself and I don't really know where to put all my "anchor link helpers" – Alexander Kuzmin Nov 19 '13 at 09:52
  • @AlexanderKuzmin You could also put it into a helper module. If you don't use the helper method in a controller action, you are fine then. Else you would have to include the helper module into your controller class by using `helper MyControllerHelper`. – Holger Just Nov 19 '13 at 10:43
1

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.

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114