【问题标题】:How to get the current route in rails如何在rails中获取当前路线
【发布时间】:2025-12-04 14:20:40
【问题描述】:

我正在构建一些 Rails 示例应用程序,其中有两个模型用户和项目。两者之间的关联是用户 has_many 项目。现在的问题是我愿意在顶部为用户的项目提供一些下拉菜单,如果有人单击该项目,它将进入项目显示页面。但是,如果用户在一个项目的编辑页面并从下拉列表中选择其他项目,我希望他能够到达新选定项目的编辑页面,以显示页面任何想法。我正在寻找的解决方案是例如:-我们可以使用 params[:controller] 找到当前控制器,使用 params[:action] 找到当前操作如何找到当前路线。 提前谢谢

如果有人想看看我的代码是什么:- 这是 github 的链接:- 'https://github.com/peeyushsingla/session_test.git/ 这里我使用的是简单的链接,但实际上我会提供一些将显示的单个下拉列表,适用于所有编辑、显示、新的每个操作

【问题讨论】:

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


    【解决方案1】:

    适用于 Rails 4

    网址示例:http://localhost:3000/allreferred?&referred_name=maria

    request.path -> "/allreferred"

    request.base_url -> "http://localhost:3000"

    request.fullpath -> "/allreferred?&referred_name=maria"

    request.original_url -> "http://localhost:3000/allreferred?&referred_name=maria"

    【讨论】:

      【解决方案2】:

      要检索 URL:

      # Current URL:
      request.original_url
      
      # Current relative URL:
      request.request_uri
      

      另外,您可以通过current_page 方法检查您是否在某个路线中。

      current_page?(my_path)
      # => true / false
      

      对于 Rails 4 使用:

      # Current URL:
      request.original_url
      
      # Current relative URL:
      request.fullpath
      

      【讨论】:

      • request.request_uri 对我不起作用(Rails 4)我必须改用用户 request.path
      • 未定义方法 current_page?
      【解决方案3】:

      你可以使用 url_for

      def current_path(params={})
        url_for(request.params.merge(params))
      end
      

      网址示例http://localhost:3000/posts

      current_path -> /posts

      current_path(order: asc) -> /posts/?order=asc

      【讨论】: