views:

2116

answers:

4

I need to know the current route in a filter in rails.. how can I find out?

I'm doing REST resources, and no named routes

+1  A: 

I'll assume you mean the URI:

class BankController < ActionController::Base
  before_filter :pre_process 

  def index
    # do something
  end

  private
    def pre_process
      logger.debug("The URL" + request.url)
    end
end

As per your comment below, if you need the name of the controller, you can simply do this:

  private
    def pre_process
      self.controller_name        #  Will return "order"
      self.controller_class_name  # Will return "OrderController"
    end
BigCanOfTuna
yes I did that, but I hoped in a better way. What I need is to know which controller has been called, but I have pretty complicated nested resources.. request.path_parameters('controller') doesn't seem to work properly to me.
luca
A: 

You can see all routes via rake:routes (this might help you).

James Schorr
rails 3.0 --> $ rake routes
Ben
+1  A: 

You can get most any data pertaining to the current path/route via the request object. This is accessible in your controller. You can read more about it here.

Take note of the "path_parameters" attribute, which returns a hash that contains the controller and the action that was requested.

Mike Trpcic
+5  A: 

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/"
controller = path[:controller]
action = path[:action]
# You will most certainly know that params are available in 'params' hash
Swanand
Would you happen to know if this is the same/right way to do it in Rails 3? I'm sure it's still accessible, but I just want to be sure that I'm adhering to the latest conventions.
John
The current controller and action are always available in `params[:controller]` and `params[:action]`. However, outside of it, if you want to recognize the route, this API is not available anymore. It has now shifted to `ActionDispatch::Routing` and I haven't tried out the `recognize_path` on it yet.
Swanand