45

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
fl00r
  • 82,987
  • 33
  • 217
  • 237
randomguy
  • 12,042
  • 16
  • 71
  • 101

4 Answers4

87
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
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • 1
    I have got ready file with bunch of answers for standart questions :) – fl00r Mar 25 '11 at 10:44
  • We used to use `params[:action]` just fine. But for some reason in the last month or so this stopped working. Now it comes up as an empty hash. However, `controller.action_name` continues to work. We're on Rails 3.2. Not sure why it stopped working, but I would suggest using `controller.action_name` as it seems more reliable. – Joshua Pinter Jan 22 '18 at 16:40
16

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
Minimul
  • 4,060
  • 2
  • 21
  • 18
13

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.

Nazar Hussain
  • 5,102
  • 6
  • 40
  • 67
5
request.parameters['controller']
request.parameters['action']
Moin Haidar
  • 1,654
  • 1
  • 16
  • 16