0

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.

2
  • You might be able to do something by overriding to_param, but that will still require you to pass the post_id into link_to. Here's some info gist.github.com/1209732 Jan 17, 2013 at 22:57
  • I think it's more then the to_param, the url is entirely different. I had thought about just doing some url redirecting though.
    – hadees
    Jan 17, 2013 at 23:23

2 Answers 2

0

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.

2
  • Why aren't you passing page as a param? Also I pretty much knew how to do this already, I was hoping to override something so that url_for(@comment) would generate the url with out having to pass in anything else.
    – hadees
    Jan 18, 2013 at 1:00
  • I put page_num on the model because that is where kaminari puts them. I think because pagination can be used for more then just displaying in the view.
    – hadees
    Jan 18, 2013 at 1:02
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.