Question

I want to create one form with 2 buttons in rails. Both forms operate on the same data in different ways, and I would prefer to keep the associated functionality in two different methods. Previously I've redirected to the appropriate method after doing a string comparision on params[:commit], but my gut says there's a better approach. Suggestions?

Was it helpful?

Solution

I also used the params[:commit] method on a form already. Using the I18n helpers makes this a bit less fragile as you can use the same lookup in the view and controller, so you don't encounter the problem that the string changes a bit.

Besides that I can only think of using JavaScript to handle the clicks on the buttons and then send the form data to different Rails actions (Maybe you can change the HTML action attribute of the form with JavaScript before you submit the form).

OTHER TIPS

Two different submit buttons that send the form to two different actions:

<%= submit_tag('Insert', :onclick=>"document.myForm.action = 'insert';") %> 
<%= submit_tag('Update', :onclick=>"document.myForm.action = 'update';") %>

Instead of "myForm" you need to put whatever is in the "name" property of your tag.

You can set that property in your default form:for tag like this:

<%= form_for(@something, :html => {:name => "myForm"}) do |f| %>

Without using JavaScript, your only solution is what you mention: checking which button was clicked by looking at the POST data in the controller. This is simply due to the nature of the HTML form element. It cannot have more than one value for its action attribute.

If you're not worried about what will happen when JavaScript isn't available, then you can write some script to change the action attribute when one of the submit buttons is clicked, prior to actually submitting the form. In the case of an ajax request, it could simply submit to the correct URL directly without altering attributes on the form.

If you're using prototype.js, you can use Form.serialize() to grab your data from your form and from there use the different buttons to post to different actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top