Redirecting Back in Rails

Often when writing Rails apps, you need to be able to redirect back to a particular page, whilst keeping GET variables in the url.

There’s a bunch of solutions out there for this kind of task, including the built in redirect_to :back but while this does work in some cases, if your needing to redirect back to an action which was two requests ago, it won’t work. You need to be able to set where it should redirect back to.

Taking inspiration from this article by Connor McKay, I decided to go down the route of using before filters to store a url path in the session, then, using a custom redirect_back method to either use the return point from the session or a passed hash.

So, lets say you have an online shop with many pages of products. You want to make it so that when a user clicks on a product on page three to see more info, then adds it to their cart, they’ll be redirected back to the third page of products rather than having to find their own way back.

class ProductsController < ApplicationController
  
  before_filter :store_return_point, :only => [:list]
  
  def list
    # List products with pagination
  end
  
  def show
    # Show details about a product
  end
  
  def add_to_cart
    # This should really be in a Cart controller, but for example's sake..
    redirect_back :action => 'list'
  end
  
end

In this example, say the url for the list action was /products/list/?page=3, it would be stored in the session and after adding a product to the cart, the user would be redirected back to that url. With the normal redirect_to :back, you’d be redirected to the ‘show’ action rather than ‘list’ with the page number.

If you want to create a back button within the UI, there’s also a link_back helper which works in the same way, if there’s a path stored in the session, it will use that otherwise it will use the url you give it.

To install in your Rails app as a plugin, run:

./script/plugin install git://github.com/idlefingers/redirect_back.git
  • By Damien on 7th January 2009 11:00am
Avatar
Shamu 19th March 2009 9:41am

Thanks a lot ! very helpful plugin !

Leave a comment..