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

一曲冷凌霜 提交于 2020-08-20 23:19:12

问题


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

回答1:


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



回答2:


In Rails 3.2 you no longer need to call controller.action_name explicitly instead just "action_name".

before_filter :check_if_locked


def check_if_locked
  puts action_name
  puts controller_name
end



回答3:


You can get full url object using

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

now you can get components as

url[:controller]

url[:action]

By default you can also use params[:controller] and params[:action] respectively during request/response life cycle.




回答4:


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


来源:https://stackoverflow.com/questions/5418454/how-to-get-requests-target-controller-and-action-with-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!