How can I find out the current route in Rails? How can I find out the current route in Rails? ruby ruby

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']) %>


To find out URI:

current_uri = request.env['PATH_INFO']# If you are browsing http://example.com/my/test/path, # then above line will yield current_uri as "/my/test/path"

To find out the route i.e. controller, action and params:

path = ActionController::Routing::Routes.recognize_path "/your/path/here/"# ...or newer Rails versions:#path = Rails.application.routes.recognize_path('/your/path/here')controller = path[:controller]action = path[:action]# You will most certainly know that params are available in 'params' hash


Simplest solution I can come up with in 2015 (verified using Rails 4, but should also work using Rails 3)

request.url# => "http://localhost:3000/lists/7/items"request.path# => "/lists/7/items"