How do you use anchors for IDs in routes in Rails 3?

前端 未结 2 824
不知归路
不知归路 2021-01-01 09:31

Imagine a blog with posts and comments. An individual comment\'s URL might be posts/741/comments/1220.

However, I\'d like to m

相关标签:
2条回答
  • 2021-01-01 09:47

    Prefer to keep your anchor builder in one place.

    class Comment
      ...
      def anchor
        "comment-#{id}#{created_at.to_i}"
      end
    end
    

    then

    post_path(comment.post, :anchor => comment.anchor)
    

    Adding the created_at.to_i obscures your data a bit more and doesn't harm anything.

    0 讨论(0)
  • 2021-01-01 10:01

    You could simply use

    redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}")
    

    to manually build the URL with the anchor. That way, you can still have the absolute URL to your comments as posts/:post_id/comments/:comment_id in your routes. You can also create a helper method in e.g. application_controller.rb

    class ApplicationController
      helper :comment_link
    
      def comment_link(comment)
        post_path(comment.post, :anchor => "comment-#{comment.id}")
      end
    end
    
    0 讨论(0)
提交回复
热议问题