我需要在Rails中的过滤器中知道当前路由。我怎么才能知道是什么?

我正在使用REST资源,没有看到命名路由。


当前回答

request.url

请求。获取除基本url之外的路径

其他回答

我假设你指的是URI:

class BankController < ActionController::Base
  before_filter :pre_process 

  def index
    # do something
  end

  private
    def pre_process
      logger.debug("The URL" + request.url)
    end
end

根据你下面的评论,如果你需要控制器的名称,你可以简单地这样做:

  private
    def pre_process
      self.controller_name        #  Will return "order"
      self.controller_class_name  # Will return "OrderController"
    end

你可以这样做:

def active_action?(controller)
   'active' if controller.remove('/') == controller_name
end

现在,你可以这样用:

<%= link_to users_path, class: "some-class #{active_action? users_path}" %>

我找到了批准的答案,请求。env['PATH_INFO'],用于获取基本URL,但如果你有嵌套路由,它并不总是包含完整路径。你可以使用request。env['HTTP_REFERER']获取完整路径,然后查看它是否匹配给定的路由:

request.env['HTTP_REFERER'].match?(my_cool_path)

你可以这样做

Rails.application.routes.recognize_path "/your/path"

它在rails 3.1.0.rc4中为我工作

我能在2015年提出的最简单的解决方案(使用Rails 4验证,但也应该使用Rails 3)

request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"