views:

40

answers:

2

In a blog in Rails I want to have paths like

http://mydomain.com/posts/28383/comments#21

This is the 21st comment of the 28383th post. The 21 is not an unique id, but the pair 28383, #21 is unique.

How can I do this in Rails? Do I have to change the routes? the model? I will be very thankful if you can point me in the right direction

Thanks

+2  A: 

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.

Ron DeVera
Thanks Ron, but where should I say that the comment_id is not a unique key? (otherwise I will have huge comment_ids)
Victor P
Can I use <a name='<%= comment.id %>' > to be able to have number-only anchors?
Victor P
Yes you can indeed.
Ryan Bigg
A: 

Ron DeVera's solution is fine. On the other hand, you may be interested in only showing one comment.

You could do this by hand with something like this in the routes.rb

map.connect 'posts/:id#:comment_id', :controller=> 'comments', :action=>'show_comment'

and then in your controller method show_comment you could access the parameter via params[:comment_id].

The rest of this solution would go forward by hand like this, including getting the comment from the post post.comments[params[:comment_id]].

Yar