In config/routes.rb
, you'll want to treat posts and comments as resources:
map.resources :posts do |post|
post.resources :comments
end
This lets you use post_comments_path(@post)
, which turns into /posts/28383/comments
.
Next, in the view that lists the post's comments, add an HTML id
attribute to each comment. For example:
<div id="comment-<%= comment.id %>">
<%= comment.body %>
</div>
Note that the HTML id
attribute is prefixed with comment-
because it must begin with an alphabetic character.
You can then link directly to a comment like this:
<%= link_to 'Comment permalink',
post_comments_path(@post, :anchor => 'comment-' + @comment.id) %>
Note that the post ID and the comment ID are used for separate things: the post ID is used to generate the base of the URL, while the comment ID is used as the anchor for jumping to the right part of the page.