#131
Oct 12, 2008

Going Back

This episode demonstrates a couple ways to redirect the user back to a previous page. Applying this to your site can help minimize the user's need to press the back button.
Tags: controllers
Download (7.6 MB, 4:51)
alternative download for iPod & Apple TV (5.8 MB, 4:51)

Full Episode Source Code

# cart_items_controller.rb
def create
  current_cart.cart_items.create!(params[:cart_item])
  flash[:notice] = "Product added to cart"
  redirect_to :back
end

# or

def create
  current_cart.cart_items.create!(params[:cart_item])
  flash[:notice] = "Product added to cart"
  session[:last_product_page] = request.env['HTTP_REFERER'] || products_url
  redirect_to current_cart_url
end
<!-- carts/show.html.erb -->
<% if session[:last_product_page] %>
  <%= link_to "Continue Shopping", session[:last_product_page] %> |
<% end %>

RSS Feed for Episode Comments 72 comments

1. Morten Oct 13, 2008 at 02:46

Useful as usual.

Good to see you still make simple Railscast suited also for Rails-beginners.


2. Per Velschow Oct 13, 2008 at 02:50

Wanted to learn a bit more about the 'request' method/object and what you can do with it. But the docs don't have much to say about it. Do you know where it is defined and what else you can do with it?


3. Sascha Oct 13, 2008 at 03:02

Thanks for these episode. Really helpful tip.


4. Richard Oct 13, 2008 at 04:01

Hi Ryan,

Thanks for your Railscasts. I am not sure if its a sign of how sad my life is at the moment but I look forward to seeing the new Railscast every monday. I used to get Crash magazine as a kid and my little heart would beat faster when I remembered that was the day that it was in the shops. Get the same feeling revery monday when I see the RSS feed, I am a newbie and much goes over my head but heh. Do I need help?

Well done & thanks.


5. Henrik N Oct 13, 2008 at 04:22

I define a redirect_back_or_default method that uses redirect_to(:back) and ActionController::RedirectBackError: http://pastie.textmate.org/private/2pc1znldyvmbencfpvf0g


6. Henrik N Oct 13, 2008 at 04:24

…since redirect_to(:back) will raise if there is no refer(r)er. I don't think you said explicitly.

Trying the link again: <a href="http://pastie.textmate.org/private/2pc1znldyvmbencfpvf0g">http://pastie.textmate.org/private/2pc1znldyvmbencfpvf0g</a>


7. Chess Oct 13, 2008 at 06:38

Wonderful screencast. This is one of those little things everyone needs to do but not everyone knows the best approach. Thanks for continuing to do the quick simple tips between the heavy hitter subjects!
 
@Richard: Your not alone, its about the only thing to look forward to on Monday! :)


8. Ryan Bates Oct 13, 2008 at 07:49

@Per Velschow, the request object is documented under ActionController:AbstractRequest which you can find here:

http://api.rubyonrails.com/classes/ActionController/AbstractRequest.html#M000808

The "env" variables (like I'm using here) can change per request. Try tossing this in a view to see the options:

<%= debug request.env %>

@Henrik, Good point! I forgot to mention the :back option will raise an exception if the referer isn't specified.


9. Austin Schneider Oct 13, 2008 at 08:33

Good episode.

What about the scenario of linking to an edit form, i.e. /products/5/edit, and after submitting it goes to /products/5/update. Redirecting back from here goes back to the edit form. I've used a few different solutions (check points, passing original_uri GET parameters, etc)

Anyone else have this issue or want to share a solution?


10. Ryan Bates Oct 13, 2008 at 16:27

@Austin, You can use the referer technique for this, but you'll have to capture it when entering the form instead of when the form is submitted. Something like this:

<%= hidden_field_tag :referer, (params[:referer] || request.env['HTTP_REFERER']) %>

Then you can use params[:referer] in the controller to redirect back.


11. Matthew Higgins Oct 13, 2008 at 16:39

In version 2.2, there's a new 'referrer' method in request.rb. This means you can simply use "request.referrer" in the controller.


12. Simon Oct 14, 2008 at 00:45

Another way to attack this problem is to have the User's URL store their previous route.
It's not ideal for every case, but if you have a lot of this stuff going on on your site (especially with polymorphic-like views), it can be handy as you don't have to manually keep tabs on the referer.

I've been playing around with putting this into a plugin for the last few weeks at:

http://github.com/toothygoose/historic_routes/tree/master

It's not totally weaponized yet, but I think the concept is sound.


13. Infakta Oct 14, 2008 at 01:57

Very usefull cast!


14. AC Oct 14, 2008 at 07:02

Since the referrer is unreliable (I always turn off sending it in my browsers), I'd suggest storing request.request_uri in session instead and using that when necessary.

http://pastie.org/292092


15. Ryan Bates Oct 14, 2008 at 08:48

@AC, that's a cool idea. But don't you need to use an after_filter instead of a before_filter so it resets at the end of the request instead of the beginning?

Also you can make exceptions using the skip_after_filter method in the controller.


16. Achim Oct 14, 2008 at 18:43

Nice Tip :-)
Very useful little screencast again


17. grosser Oct 15, 2008 at 22:38

please also mention the most obviouse choise:

link_to 'Continue', :back


18. Kevin Nolan Oct 16, 2008 at 09:12

Ryan,

This has nothing to do with this Railscast, but I have a suggestion for a Railscast topic.

Would you please do a Railscast on the usage of html frames w/in Rails, particularly if the contents of those frames are dynamic. I'm not sure that this is even possible, but I would love to know for sure.

Thanks,

kevin


19. Развод фирменных магазинов Oct 16, 2008 at 14:39

What about the scenario of linking to an edit form, i.e. /products/5/edit, and after submitting it goes to /products/5/update. Redirecting back from here goes back to the edit form. I've used a few different solutions (check points, passing original_uri GET parameters, etc)


20. Austin Schneider Oct 17, 2008 at 08:18

Wow, spammers are copying others comments. That's a new one.


21. Matthijs Langenberg Oct 17, 2008 at 09:13

I think I'll choose for not using the session, but have the browser keeping state by appending the continu shopping url to the show cart URL.


22. Jaime Iniesta Oct 18, 2008 at 05:23

Thanks! A simple technique and a great tutorial.

We have to keep in mind that request.env['HTTP_REFERER'] doesn't exist on the test environments in case you're testing the redirect!


23. Heiko Webers Oct 20, 2008 at 10:20

When using params with the redirect_to method be aware of the security implications. Check out my blog post and the "Response Splitting" post in the Rails weblog.


24. Rechnung Oct 21, 2008 at 14:55

Usefull cast! Thank you!


25. Mick Staugaard Oct 28, 2008 at 01:53

Using the helper method link_to with the :back option would be the best for displaying the "Continue shopping" link.

link_to('Continue shopping', :back)

This is better because it will link to the referrer if it is present or "javascript:history.back()" when there is no referrer.


26. Mark Karp Oct 29, 2008 at 21:50

I am trying to use the redirect_to :back from an action, but I am using restful_authentication, and the action requires the user to be logged in (I have a before_filter :login_required in the controller), so when I am already logged in the :back works fine, but when it redirects first to the login page, when it gets to the redirection in my action, it tries to go back to /session/new...

Is there any easy way to fix this?


27. Christian Dec 31, 2008 at 06:25

You are the BEST!!!


28. Sam Feb 06, 2009 at 02:01

@Ryan "But don't you need to use an after_filter instead of a before_filter so it resets at the end of the request instead of the beginning?"
Yes, must use a after_filter, that's exactly how I implement mine. Plus it keeps it from muddying up the controller.


29. Baby heart monitor Oct 18, 2009 at 03:24

Thanks again for the great guide.


30. Teeth Whitener Nov 02, 2009 at 01:12

Now this code will help me I my latest project.Thanks For posting it..


31. Acai Berry Nov 19, 2009 at 21:51

I implemented this code and I found that it was working well.


32. Seattle Cheap Flights Dec 11, 2009 at 21:41

Why do so many people want ugg boots.


33. Jenny Johnson Dec 18, 2009 at 07:48

Very useful. Thanks.


34. acai berry blast Dec 20, 2009 at 18:00

Thanks that's helpful..


35. hoodia super slim Dec 24, 2009 at 08:21

Great blog with great information.Thanks Buddy


36. cellulean Dec 26, 2009 at 21:24

will this automatically create a button for my visitors to go to the previous page? Rather than going to the top and press the back button?


37. Stop Sweating Dec 26, 2009 at 21:25

nice info you have here, this code will be really helpful


38. how to get rid of eczema Dec 26, 2009 at 21:26

I tried the code and it worked perfectly, thanks alot


39. Gamefly Dec 27, 2009 at 22:01

I also used this functionality through this code and got success.


40. Reverse Phone Lookup Dec 30, 2009 at 02:42

Yes!! I get frustrated by pressing back again and again.


41. warm mist humidifiers Dec 30, 2009 at 09:25

good very helpful codes


42. easy online loans Dec 30, 2009 at 16:36

Cool info..useful.


43. Reverse Phone Lookup Dec 30, 2009 at 22:59

I was searching for information on Railscast, and google directed me to this page.


44. Reverse Phone Lookup Dec 30, 2009 at 23:01

Nice informative post.


45. Gamefly Dec 30, 2009 at 23:12

I didn't get how to minimize the use of back button either we have to download or upload the code.


46. Payday Loan Jan 03, 2010 at 12:09

I was searching for information on Railscast, and google directed me to this page.


47. bowtrol Jan 07, 2010 at 10:58

This is a great info here.Thanks


48. netflix Jan 08, 2010 at 20:14

I used to get Crash magazine as a kid and my little heart would beat faster when I remembered that was the day that it was in the shops.


49. Criminal Background Check Jan 10, 2010 at 22:47

It is very nice coding. This coding will very beneficial for our sites because by this coding user can visit one page to another page.


50. how to get pregnant Jan 12, 2010 at 21:14

Its really very helpful code that you shared thanx a lot for this.


51. Blockbuster Jan 12, 2010 at 23:16

Thanks for the post. Idea behind your post is interesting.i would like to read more from you.


52. Blockbuster Jan 13, 2010 at 02:14

Thanks for sharing sch an interesting and informative post.


53. Criminal Background Check Jan 13, 2010 at 22:37

Nice informative post thanks for sharing with us.


54. Criminal Background Check Jan 14, 2010 at 01:54

I used your code in my project. Your code is fully operational.


55. Payday Loans Jan 17, 2010 at 21:14

I think episode has really reduced the overhead of pressing back button to show the previous page.


56. how to get a six pack Jan 18, 2010 at 15:24

Its a great informaive blog.Awesome


57. Gewichtsverlust Jan 23, 2010 at 20:59

Thanks, the code works perfectly


58. Syntra Jan 23, 2010 at 21:00

Thanks for posting. Idea behind your post is interesting.i would like to read more from you.


59. Syntra Jan 23, 2010 at 21:01

I have bookmarked you page, hopefully you add some more codes for us to use.


60. javon Jan 25, 2010 at 22:32

 hopefully you add some more codes for us to use.


61. Criminal Background Check Jan 26, 2010 at 22:58

Redirecting using your code is very easy. If you some more details about this then please share it with me.


62. colon cleanse Jan 26, 2010 at 23:00

Thank you for this useful information.I will share it with my friends.I have done it bookmark.


63. Gamefly Feb 02, 2010 at 14:11

Thanks...code is still useful !


64. Reverse Phone Lookup Feb 02, 2010 at 23:37

You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!


65. Reverse Phone Lookup Feb 02, 2010 at 23:38

I found your blog from google and read a few of your other posts.They are incredible. Please keep it up... have a nice day.


66. Stretch Marks Feb 04, 2010 at 02:58

Hi people,
Well I am new here and really enjoyed reading the article.
Thanks for sharing this great piece of information.Do keep us update with some more great articles.


67. travail sur internet Feb 05, 2010 at 00:30

I found your blog from google and read a few of your other posts. They are incredible. Please keep it up… have a nice day.


68. James Feb 06, 2010 at 03:09

thanks for this.very interesting and useful.


69. copywriting Feb 06, 2010 at 05:37

this information is very nice and activities post. I hope it will get more benefit to me.


70. Acnezine Feb 06, 2010 at 08:52

Top info deserve a big thanks.love it!

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source