Sunday, February 11, 2007

A link back to referring page in Rails

So here's the quick problem. You have a long list of records in your rails application, such as posts. You end up using the standard pagination offered in rails, which we all know is slow. Regardless, it's pretty annoying to go down into an individual post, edit it in-place, and then hit the back button, since there's no link back to the previous page.

Well, since it's a pagination, there's not a static page to link a "back to list" link. You could pass in the page, but that's a pain in the butt. It's much easier to do:

<%= link_to "Back up to list", request.env["HTTP_REFERER"] %>

This'll put a link back to the same page in the pagination list that you came from. Saves pains. Ends up reading the HTTP spec on headers is a helpful, in addition to some Rails source.

Ends up that "redirect_to :back" also uses the same trick. You can use that in your controller to just redirect back to whatever method called it.


  1. I know this is an old post, but I'd like to point out that:

    <%= link_to "Back up to list", :back %>

    will accomplish the same thing, and if there isn't a referrer, it will use the javascript:history.back() method..

  2. Yup, thanks. This was before link_to :back was available. But it's good that people that find this will get updated.

  3. Vidyarthi3:53 AM

    Oh..gud but you can also make it as

    <%= link_to 'Go Back', request.referer %>

  4. I have a similar issue. But both :back and request.referer causes the previous page contents to reset to nil, losing what data already entered. How to avoid this?