how to submit 2 forms with one button rails 3

2019-07-27 00:41发布

问题:

I want to submit two forms with a single button.

Below if my code :-

rate.rb

belongs_to :target, :polymorphic => true
belongs_to :location

location.rb

has_many :rates

event.rb

has_many :rates, :as => :target

form.html.haml

= form_for [@event, @rate] do |form|
                    %ul
                        %li= form.radio_button :rate, "Excellent"
                        %li Excellent
                        %li= form.radio_button :rate, "Okay"
                        %li Okay
                        %li= form.radio_button :rate, "Poorly organized"
                        %li Poorly organized
                        %li= form.radio_button :rate, "Didn't happen"
                        %li Didn't happen

=form_for [@event.location, @rate] do |form|
                    %ul
                        %li= form.radio_button :rate, "Excellent"
                        %li Excellent
                        %li= form.radio_button :rate, "Okay"
                        %li Okay
                        %li= form.radio_button :rate, "Nothing special"
                        %li Nothing special

How can this be done ?

回答1:

I was in same situation today and did:

in form.html.haml add a link: (I wrote in ERB)

<%= link_to "Save", "#", :class => 'button_submit' %>

Assuming form ids as "form1" and "form2" in some coffee file:

rates.js.coffee

jQuery ->
  $(".button_submit").live "click", (e) ->
    e.preventDefault()
    $("#form1").trigger "submit"
    $("#form2").trigger "submit"

That's it!