简体   繁体   中英

Rails Jquery How to submit multiple forms via ajax

I have a form with a has_many association and I would like to submit multiple forms via ajax so the parent form's show page can be updated dynamically.

I have the following models (they are in mongoid but i don't think it matters between mongoid and activerecord):

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  has_many :tasks
end

class Task
  include Mongoid::Document
  include Mongoid::Timestamps
  belongs_to :user, inverse_of: :tasks
end

I have a form which renders n partials of the form:

<%= form_for @task, remote: true do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %>

for new tasks on the show.html.erb for user via ajax.

How can i write a single submit button on the show.html.erb to submit all of the tasks at once while associating them with the parent user?

Based on the second answer to this question: Rails 3: How to trigger a form submission via javascript?

Say you have a button with an id called #multiSubmit , then you can submit each form when it is clicked using the following JavaScript:

$(function() {
  $("#multiSubmit").click( function() {
    $('form').each(function(i, item) {
      $(item).trigger('submit.rails');
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM