开发者

How to create one form with many possible actions in Rails?

开发者 https://www.devze.com 2022-12-08 02:04 出处:网络
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 meth开发者_如何学编程

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 meth开发者_如何学编程ods. 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?


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.


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号