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

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


当前回答

你可以这样做

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"

根据@AmNaN的建议(更多细节):

class ApplicationController < ActionController::Base

 def current_controller?(names)
  names.include?(params[:controller]) unless params[:controller].blank? || false
 end

 helper_method :current_controller?

end

现在你可以调用它,例如在导航布局中标记列表项为活动:

<ul class="nav nav-tabs">
  <li role="presentation" class="<%= current_controller?('items') ? 'active' : '' %>">
    <%= link_to user_items_path(current_user) do %>
      <i class="fa fa-cloud-upload"></i>
    <% end %>
  </li>
  <li role="presentation" class="<%= current_controller?('users') ? 'active' : '' %>">
    <%= link_to users_path do %>
      <i class="fa fa-newspaper-o"></i>
    <% end %>
  </li>
  <li role="presentation" class="<%= current_controller?('alerts') ? 'active' : '' %>">
    <%= link_to alerts_path do %>
      <i class="fa fa-bell-o"></i>
    <% end %>
  </li>
</ul>

对于users和alerts路由,current_page?这就足够了:

 current_page?(users_path)
 current_page?(alerts_path)

但是使用嵌套路由和请求控制器的所有动作(与项目相比),current_controller?对我来说是更好的方法

 resources :users do 
  resources :items
 end

第一个菜单项是为以下路由激活的方式:

   /users/x/items        #index
   /users/x/items/x      #show
   /users/x/items/new    #new
   /users/x/items/x/edit #edit

我假设你指的是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

要查找URI:

current_uri = request.env['PATH_INFO']
# If you are browsing http://example.com/my/test/path, 
# then above line will yield current_uri as "/my/test/path"

找到路径,即控制器,动作和参数:

path = ActionController::Routing::Routes.recognize_path "/your/path/here/"

# ...or newer Rails versions:
#
path = Rails.application.routes.recognize_path('/your/path/here')

controller = path[:controller]
action = path[:action]
# You will most certainly know that params are available in 'params' hash

你可以这样做

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

它在rails 3.1.0.rc4中为我工作