Ruby on rails 如何获取请求';s目标控制器和Rails 3的操作?
在应用程序控制器中筛选之前Ruby on rails 如何获取请求';s目标控制器和Rails 3的操作?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,在应用程序控制器中筛选之前 class ApplicationController < ActionController::Base before_filter :authenticate def authenticate # How do we know which controller and action was targetted? end end class ApplicationController
class ApplicationController < ActionController::Base
before_filter :authenticate
def authenticate
# How do we know which controller and action was targetted?
end
end
class ApplicationController
您可以使用
url=Rails.application.routes.recognize_path(request.env['path_INFO'])
现在,您可以根据需要获取组件
url[:controller]
url[:操作]
默认情况下,您还可以在请求/响应生命周期中分别使用params[:controller]
和params[:action]
class ApplicationControllerclass 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
前过滤器:验证
def身份验证
#我们如何知道针对哪个控制器和操作?
参数[:控制器]
参数[:操作]
#或
controller.controller\u名称
controller.action\u名称
结束
结束
在Rails 3.2中,您不再需要显式调用controller.action\u name,而只需调用“action\u name”
在请求/响应周期外非常方便,但在此过程中绝对不需要。此代码非常方便解析存储在某个字符串变量中的url。编辑答案以在请求/响应周期内使用。这仅适用于HTTP GET方法的请求。要支持所有方法,请使用
url=Rails.application.routes.recognize_path(request.env['path_INFO'],{:method=>request.env['request_method']})
。我已经准备好了一个文件,其中包含一系列标准问题的答案:)我们以前使用params[:action]
很好。但由于某种原因,在过去的一个月左右,这停止了工作。现在它变成了一个空散列。但是,controller.action\u name
继续工作。我们在轨道3.2上。不确定它为什么停止工作,但我建议使用controller.action\u name
,因为它看起来更可靠。我更喜欢这个参数,因为它去掉了路径前缀,只给出了控制器名称。
before_filter :check_if_locked
def check_if_locked
puts action_name
puts controller_name
end
request.parameters['controller']
request.parameters['action']