2

Instead of checking if controller_name == 'foo' && action_name == 'bar', is there a Rails method to return the two in the same format that you'd define them in the routes.rb file (get '/buzz' => 'foo#bar')?

Is there something like get_current_route() that'll return "foo#bar"?

Andrei
  • 1,121
  • 8
  • 19
  • 2
    That format is pretty much unique to the routing system and isn't used elsewhere, and even then it's just a shorthand for two slightly longer options. What's the use case here? – tadman Mar 31 '17 at 21:44
  • Avoiding this: `if (controller_name == 'foo' && action_name == 'bar') || (controller_name == 'foo2' && action_name == 'bar2')` – Andrei Mar 31 '17 at 21:48
  • 1
    Make a look-up table: `MAGIC_ROUTES = [ %w[ foo bar ], %w[ foo2 bar2 ] ]` and then `MAGIC_ROUTES.include?([ params[:controller], params[:action] ])` – tadman Mar 31 '17 at 21:51
  • @tadman This sounds like a painful way to maintain a duplicated list of routes – Andrei Mar 31 '17 at 22:17
  • It sounds painful that you've got duplicated routes. Is there any reason why you're concerned about the originating route? – tadman Apr 01 '17 at 00:29

2 Answers2

2

You can get names of your current controller and action by using controller_name and action_name methods. So you can concatenate strings to get desired result.

Also you can get these values from params hash its considered as a bad practise to do so.

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values

ActionController Parameters

Reference links:

Rails - controller action name to string

Can I get the name of the current controller in the view?

Community
  • 1
  • 1
Martin
  • 4,042
  • 2
  • 19
  • 29
1

I'm not aware of one.

But you can always write your own and stick it somewhere convenient:

e.g.:

module ApplicationHelper

  def get_current_route
    "#{params[:controller]}##{params[:action]}"
  end

end
James Milani
  • 1,921
  • 2
  • 16
  • 26