Ruby-on-rails 如何使用 Rails 3 获取请求的目标控制器和操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5418454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get request's target controller and action with Rails 3?
提问by randomguy
In the application controller before filter.
在过滤器之前的应用程序控制器中。
class ApplicationController < ActionController::Base
before_filter :authenticate
def authenticate
# How do we know which controller and action was targetted?
end
end
回答by fl00r
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
回答by Minimul
In Rails 3.2 you no longer need to call controller.action_name explicitly instead just "action_name".
在 Rails 3.2 中,您不再需要显式调用 controller.action_name 而只是“action_name”。
before_filter :check_if_locked
def check_if_locked
puts action_name
puts controller_name
end
回答by Nazar Hussain
You can get full url object using
您可以使用获取完整的 url 对象
url = Rails.application.routes.recognize_path(request.env['PATH_INFO'])
url = Rails.application.routes.recognize_path(request.env['PATH_INFO'])
now you can get components as
现在你可以得到组件
url[:controller]
url[:controller]
url[:action]
url[:action]
By default you can also use params[:controller]and params[:action]respectively during request/response life cycle.
默认情况下,您还可以在请求/响应生命周期中分别使用params[:controller]和params[:action]。
回答by Moin Haidar
request.parameters['controller']
request.parameters['action']

