Redirecting in Rails

Frequently, with websites, you need to redirect the user from one page to another. In particular, redirects are useful because they follow the DRY (Don’t Repeat Yourself) methodology–things stay in one place, and you don’t have duplicate code.

Rails provides a convenient redirect_to method–it allows you to redirect the user to a different website. You can use it to redirect to different actions within a controller, or to relative or absolute URLs.


redirect_to :action => "edit", :id => 7
redirect_to :back # go to the previous page

redirect_to "/status/view/index.html"
redirect_to "http://www.google.com"

Notice how easy redirects are in Rails–you don’t need to specify any Javascript or META tags; Rails handles all the details. Some useful places you can use a redirect for include:

  • Redirecting users to a login screen when they try and access registered-only pages
  • Tracking links clicked by linking to a tracker action, then redirecting to the real resource
  • Backtracking when errors occur

You are only limited by your imagination! Redirects are helpful in many, many situations. Best of all, you can test your redirects in functional tests (for a single controller) or integration tests (for redirects from one controller to another).

One word of caution–you can only redirect once. If you redirect twice, it will cause an error. If you have a redirect and a render action in the same block of code, that will cause an error, too.

You can find the full API for redirect_to here.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , . Bookmark the permalink.

3 Responses to Redirecting in Rails

  1. I’ve been pretty impressed with RoR so far but am far from impressed with the redirect capabilities. The practice of redirecting from an action while passing parameters is subpar at best. I shouldn’t have to jump through hoops just to redirect and have it include the parameters. Additionally, I still haven’t figured out how (or if) you can redirect from an action to an external site while still passing the parameters. Overall RoR is pretty cool, but redirects kind of suck.

  2. ashes999 says:

    Redirecting to an external site sounds like a security loophole :) what are some legitimate use-cases of something like this?

  3. Aaron says:

    Yes, I would also like to know how to redirect to another website without using javascript.