[ruby-on-rails] Rails - controller action name to string

I have a Rails question.

How do I get a controller action's name inside the controller action?

For example, instead of

def create
  logger.info("create")
end

I want to write something like

def create
  logger.info(this_def_name)
end

What is a way to get this_def_name?

This question is related to ruby-on-rails function

The answer is


mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.

found out it's possible with self.current_method

easily found at http://www.ruby-forum.com/topic/75258


controller name:

<%= controller.controller_name %>

return => 'users'

action name:

<%= controller.action_name %>

return => 'show'

id:

<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>

return => '23'


I just did the same. I did it in helper controller, my code is:

def get_controller_name
  controller_name    
end


def get_action_name
  action_name   
end

These methods will return current contoller and action name. Hope it helps


This snippet works for Rails 3

class ReportsController < ApplicationController

  def summary
    logger.debug self.class.to_s + "." + self.action_name
  end

end

will print

. . .
ReportsController.summary
. . .


In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.