Search code examples
ruby-on-railsruby-on-rails-3routesactionview

Customizing what url_for returns for a model?


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.


Solution

  • 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