Redirecting back

by

It’s very common in Rails CRUD to have a create and update actions that redirect back to the show action. The idea is that you show an object, click edit, save, go back to showing said objects with your changes.

All is fine until you have an edit link somewhere else. Let’s say you have an edit link in the listing of the CRUD, when someone uses you have to go back to the listing, not the show.

Well, Ruby on Rails provides just the thing for that:

redirect_to :back

That will send you back wherever you came from. The problem with that is that it will raise an exception if there’s no HTTP_REFERER, so you’ll have to write something like this:

begin
  redirect_to :back
rescue ActionController::RedirectBackError
  redirect_to somewhere_else
end

Of course there’s a pattern, so almost all my projects, at one time or another end up with this snippet of code in the application controller:

def redirect_back_or_to(*args)
  redirect_to :back
rescue ActionController::RedirectBackError
  redirect_to *args
end

I really like how every method is an implicit begin, it really looks beautiful. Then you just do:

redirect_back_or_to somewhere_else

I’m surprised Rails didn’t come with something like that out of the box, or maybe I just missed.

You may also like:

If you want to work with me or hire me? Contact me

You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 5,043 other subscribers

I wrote a book:

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I’ve been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Kubuntu Lisp management Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek technology Ubuntu web Windows WordPress

I’ve been writing for a while:

Mastodon

%d