【问题标题】:How do you use anchors for IDs in routes in Rails 3?在 Rails 3 中,如何在路由中使用锚点作为 ID?
【发布时间】:2011-02-12 22:26:11
【问题描述】:

想象一个包含postscomments 的博客。单个评论的 URL 可能是 posts/741/comments/1220

但是,我想将 URL 设为 posts/741#1220,甚至是 posts/741#comment-1230

这样做最不干扰的方式是什么,以便redirect_to comment_path(my_comment) 指向正确的 URL?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routing anchor


    【解决方案1】:

    你可以简单地使用

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

    使用锚点手动构建 URL。这样,您仍然可以在路由中将 cmets 的绝对 URL 设为 posts/:post_id/comments/:comment_id。您还可以在例如创建一个辅助方法。 application_controller.rb

    class ApplicationController
      helper :comment_link
    
      def comment_link(comment)
        post_path(comment.post, :anchor => "comment-#{comment.id}")
      end
    end
    

    【讨论】:

    • 让我的绝对 URL 仍然是 posts/:post_id/cmets/:comment_id 有什么好处?
    • @ClosureCowboy:您仍然可以正确地将 cmets 定义为资源,例如删除或编辑它们。这是否有意义取决于您的实际要求。
    • 控制器真的是放置这种助手的最佳位置吗?我自己也在思考这个问题,我真的不知道把我所有的“锚链接助手”放在哪里
    • @AlexanderKuzmin 您也可以将其放入帮助模块中。如果您不在控制器操作中使用辅助方法,那么您就可以了。否则,您必须使用 helper MyControllerHelper 将帮助模块包含到您的控制器类中。
    【解决方案2】:

    更喜欢将锚生成器放在一个地方。

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

    然后

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

    添加created_at.to_i 会使您的数据更加模糊,并且不会造成任何损害。

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多