Simple, user-friendly cancel links for your Rails forms
June 16, 2011
The default Rails view generator includes back links on form-related view templates, so if users change their mind they can easily get out of the form and on to something else. However, these links are static. What do you do if you allow users to access the form from multiple views (say, an index and a show).
Here’s a simple but effective solution I came up with: Instead of passing a static URL, I pass the HTTP referrer environment variable as the location. That way users are taken back to the page from which they opened the form to begin with.
Here’s how it works. Most of the code resides in the
You’ll need to include
Rails.application.routes.url_helpers in order to access
link_to from a helper method. Then you add the helper method itself, which does nothing more than return a cancel link. Mine uses an old-style
:confirm message; you can spruce it up with some less obtrusive if you’d like.
If I need a cancel link in a view, I just add
The result: a flexible, reusable cancel option that’s much more user-friendly. Not bad for just a few lines of code.
blog comments powered by
Rails testing made simple
Learn to test Rails apps the way
I learned, building up tests step-by-step, in
Everyday Rails Testing
Expanded to include exclusive content and a complete sample Rails application.
Learn more »