Ruby On Rails Controller Path

With Ruby on Rails, you can redirect to or link to an action in different controller. For example, to redirect to the login action in the account controller you can use the following from withing a controller in you rails application:

redirect_to :controller => 'account', :action => 'login'

When this redirect statement is executed you application will redirect to a URL like the following:

http://localhost:3000/myapp/account/login

The controller value is like a fragment of URL and can refer to a controller relative to your current controller location or can be absolute to you rails application. Because you can place controllers in their own directories under the app/controllers you can easily imagine having an admin/user_controller. In this case, from the user controller you can refer to another controller that is at the root level by the following:

redirect_to :controller => '../account', :action => 'login'

The controller portion of the redirect to, the ‘../account’ part, is relative to your current controller. To refer to a controller with an absolute path you can do the following:

redirect_to :controller => '/account', :action => 'login'

The controller portion of a redirect is really just a path which can be relative to your current controller or absolute to your rails application and the rails routing will do the right thing for you. This same logic applies to the link_to function.

Technorati Tags: , , ,