How can I find out the current route in Rails?

If you are trying to special case something in a view, you can use current_page? as in:

<% if current_page?(:controller => 'users', :action => 'index') %>

…or an action and id…

<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>

…or a named route…

<% if current_page?(users_path) %>

…and

<% if current_page?(user_path(1)) %>

Because current_page? requires both a controller and action, when I care about just the controller I make a current_controller? method in ApplicationController:

  def current_controller?(names)
    names.include?(current_controller)
  end

And use it like this:

<% if current_controller?('users') %>

…which also works with multiple controller names…

<% if current_controller?(['users', 'comments']) %>

Leave a Comment