Cancel Forms And Avoid The If Then Statements
One of the big pains with Rails form helpers is that they don’t have a cancel button. No, problem – that is easy enough to add in. Just use a second submit tag like so:
Now, if the user clicks the “Cancel” button a “commit” param with a value of “Cancel” will be submitted.
This is nothing earth-shattering. I have found this technique on various blogs. But then they all suggest checking for this parameter in the update or create method of your controller. I don’t like this because it makes you add in extra “if-then” statements. I really hate “if-then” statements. They make the code so much harder to read.
So what to do?
Use a before filter.
Then add in your method to check for the cancel parameter in the commit message.
That’s it. So now, if anyone clicks on the “Cancel” button on an edit or new form they will be redirected to the index.
If you really wanted to you could make the Cancel button submit the cancel parameter as part of the model hash. You would do it like this:
You would just need to update your check_for_cancel method to check for that param. I prefer the previous method though since it is more generic.
October 16th, 2008 at 10:01 am
What is the thought behind using a submit-button for cancel? It seems a regular button with an onclick-handler would be superior for the task?
October 16th, 2008 at 10:52 am
@jx – Could be. I just did the above because I am lazy. I also modified the “checkforcancel” method to redirect to the show action if there is an id param and the index action if there isn’t. That way it is properly handling canceling from a “new” form and an “edit” form.
onclick would probably work just fine – I just like the look of:
submit_tag "Cancel"in my views.January 30th, 2010 at 5:29 pm
Thanks, worked like a charm
July 30th, 2010 at 5:50 am
Nice solution, thanks. @jx if I understand you correctly, what would happen if javascript was turned off?