关于ruby:如何使用Rails 3获取请求的目标控制器和操作?

How to get request's target controller and action with Rails 3?

在应用程序控制器前过滤。

1
2
3
4
5
6
7
class ApplicationController < ActionController::Base
  before_filter :authenticate

  def authenticate
    # How do we know which controller and action was targetted?
  end
end


1
2
3
4
5
6
7
8
9
10
11
12
class ApplicationController < ActionController::Base
  before_filter :authenticate

  def authenticate
    # How do we know which controller and action was targetted?
    params[:controller]
    params[:action]
    # OR
    controller.controller_name
    controller.action_name    
  end
end


在Rails3.2中,您不再需要显式地调用controller.action_name,而只需调用"action_name"。

1
2
3
4
5
6
7
before_filter :check_if_locked


def check_if_locked
  puts action_name
  puts controller_name
end


您可以使用

url = Rails.application.routes.recognize_path(request.env['PATH_INFO'])

现在您可以获得组件

url[:controller]

url[:action]

默认情况下,您也可以在请求/响应生命周期中分别使用params[:controller]params[:action]


1
2
request.parameters['controller']
request.parameters['action']