Jake Worth

Jake Worth

Rails Action Name Method

Published: October 07, 2015 2 min read

  • ruby

Today I was trying to control what rendered on a page based on which controller action called it, and discovered the action_name method. It’s located in actionview:

pry> method(:action_name).source_location
=> ["/Users/jake/.rvm/gems/ruby-2.2.3/gems/actionview-4.2.4/lib/action_view/helpers/controller_helper.rb", 10]

Add this to your view code, and it you’ll get the relevant action:

pry> action_name
=> "index"

Same partial, different context:

pry> action_name
=> "drafts"

This method would allow conditionals like this (HAML):

- if action_name == 'index'
  Welcome to the index.
- else
  Welcome to the drafts.


Get better at programming by learning with me. Subscribe to my newsletter for weekly ideas, creations, and curated resources from across the world of programming. Join me today!