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.