Cancel Forms And Avoid The If Then Statements
October 16th, 2008One 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.
