Pregunta

I have a post model that has many comments. Now a link to a comment is actually a url like so /post/1?page=3#26.

What I want to be able to do is call link_to "foobar", @comment and have it generate the correct url. I already know how to calculate the page a comment is on so you can assume @comment.page_num will return the correct integer.

I think this is going to require customizing the polymorphic_url somehow.

If it can't easily be done maybe I need a helper function link_to_comment but I'd like it to be able to do everything link_to can, ie passing blocks and what not.

¿Fue útil?

Solución 2

So this is what I ended up doing. It pretty simple but does exactly what I need. My original scope might have been too ambitious. Classic case of keep it simple stupid.

module CommentsHelper

  def comment_page_url(comment)
    post_url(comment.post, page: comment.page_num, anchor: comment.id)
  end

end

Otros consejos

I think something like this would work:

link_to "foobar", @post, href: "#{url_for(@post)}?page=#{@comment.page_num}"

This is assuming that page_num returns 3#26 which is an assumption I'm not terribly confident about, but I think you can figure it out from there.

One more comment to think about. Is page_num really a vital attribute of the Comment class? It seems to me that it's a formatting concern and probably belongs in a helper function instead of the Model. Just something to think about.

I hope it helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top