-->

When autosaving w/jQuery, how do I submit a form t

2019-08-28 06:26发布

问题:

A follow up to this question: what's a RESTful way to save draft posts?

I'm wondering, the submissions that are created always submit to the "create" action in rails. How can I make:

  1. The first autosave create an entry
  2. All subsequent autosaves update the saved entry
  3. The final submission update the same entry

For information, see the related question first. Also, I'm doing this on the Post model, where I added a field "draft" that can be true or false. My jQuery submission is:

 $(document).ready(function() {
    $('#new_post').append('<div class="temp"> </div>');
    setInterval(function() {

      { $('#new_post .temp').html('<input type="hidden" name="post[draft]" id="post_draft" value="true" />');
  draft = $('#draft');
}

      $('#post_form form[data-remote]').submit();

     $('#new_post .temp').html('');
      }, 1000*30); // 1000ms * 60s = 1m

 });

This file creates a hidden field "draft", submits the form, and then deletes the field.

Also, another file that may be of use is create.js.erb. Once the form is submitted to the controller, this embedded ruby javascript file is called and run. Currently, I make a variable "draft" available to the file such that:

 <% if draft %>
      #maybe putting code here can change the form to submit to "update" action next time?
 <% else %>
      # code that executes if it's a final submission, updating tables etc..
 <% end %>

Maybe this file is a place to accomplish my task?

If there is more information required, let me know.

回答1:

Maybe you can try this: After you get back the post id from the first ajax form submit, you can modify subsequent form submit to supply the post id and change the form method from POST to UPDATE. That should be a restful way of triggering record updates.