Rails: Add form button, cancel action?

I’ve looked for this on google, but didn’t find anything. How can I add a cancel action to a form? When I add a submit_tag, it just does an update or new action.

  • matt

You can look around here:
http://api.rubyonrails.com/

My 5 minute search looking in the FromHelpers and other various views turned up nothing. You could always write your own helper though, a clear button is not too hard :wink:

I normally implement cancel buttons as a javascript button (i know it’s sorta evil) in most cases as they are on admin backends. Otherwise, I guess you can make the controller decide what to do based on the value of the submit tag

Here’s a cancel button & a submit button

<%= submit_tag ‘Cancel’ %>
<%= submit_tag ‘Update’ %>

Your controller can differentiate which button was pressed too:

def edit()

if request.get?
	     @institution = Institution.find(params[:id])
elsif request.post?
    if params[:commit].eql?('Cancel')
        redirect_to(:action=&gt;'view', :id=&gt;params[:id])
        return nil
    else
        @institution = Institution.find(params[:id])
		if @institution.update_attributes(params[:institution])
  		    flash[:notice] = 'Institution was successfully updated.'
  		    redirect_to(:action=&gt;'view', :id=&gt;@institution)
		end
    end
end

end

Cancel buttons are step-dependent and application-dependent.

Suppose, for example you have a shopping cart. At the first step (say, log in) cancel should probably send you back to the cart screen (the last page). But say 3 steps in, should it still redirect to the previous screen? No, it should go to the cart screen again.

Thus, no helper tags :slight_smile: Use something similar to Sevenwulf suggested and you should be good to go.