redirect_to :back
Posted: November 5th, 2008 | Author: Pierre Olivier Martel | Filed under: Rails | 1 Comment »Here’s a useful trick I didn’t know about! The command redirect_to :back does just what it says, it redirects the user back to the previous action. This is similar to redirect_to(request.env["HTTP_REFERER"]).
The Rails documentation states that this can be useful for forms that are triggered from multiple places.
In my case I needed it to redisplay the same page after a post that didn’t validate. I could redirect the user back to the right action but some request parameters were missing in the post action that prevented this to work right.
For example, if the last request was /my_action?location=there, I would lose the location parameter if I didn’t send it along in the post. And I didn’t want to send the parameter along since I was calling a different controller which business logic didn’t relate to these parameters.
Well, by using the HTTP referer, Rails redirects back to the URL with the right parameters and sends the user to the exact same location he was. Neat!
Passionate web entrepreneur living in Montreal and hacking (mostly) Facebook apps with Ruby on Rails.