Jquery Rails 3… form submits twice… deletes twice…

2019-01-25 22:26发布

问题:

It seems like eveyone has this problem but no one has a laymans terms answer or even a proper solutions.

I have a form that uses ajax to submit the form and automatically adds it to the list below the text field. The form submits twice so i have two identical (apart form the ID) records. Worse still is when you try to delete it wont renew the page because its tried to delete the same record twice.

I hope someone has a great answer out there... btw im new to rails. code:

index.html.erb

<h1>SSCC</h1>
<div id="orderline_form">
    <%= render 'form' %>
</div>

<ul id="orderlines">
    <%= render :partial => @orderlines.reverse %>
</ul>

_form.html.erb

<%= form_for(@orderline, :remote => true) do |f| %>
<div class="field">
    <%= f.label :Order_ID %>
    <%= f.text_field :order_id %><br/>
    <%= f.label :SSCC %>
    <%= f.text_field :sscc %>
</div>
<div class="actions">
    <%= f.submit %>
</div>
<% end %>

_order_line.html.erb

<%= content_tag_for(:li, order_line) do %>

<%= order_line.id %> |
<%= order_line.order_id %> |
<%= order_line.sscc %>
(<%= link_to 'Delete', order_line, :confirm => 'Are you sure?',
:method => :delete, :remote => true %>)

<% end %>

create.js.erb

$('#orderlines').prepend('<%= escape_javascript(render(@orderline))%>');
$('#orderlines > li:first ').effect('highlight', {}, 3000);
$('#orderline_form > form')[0].reset();

destroy.js.erb

$('#<%= dom_id(@orderline) %>').css('background', 'red');
$('#<%= dom_id(@orderline) %>').hide("fade", {}, 1500);

回答1:

It happened to me that "application.js" was stored twice (.../public/assets/application.js and .../app/assets/javascripts/application.js). The Rails 3.2.1 Asset pipeline compiled it and created another one. Check for that and delete the unneeded.

Keep in mind that you might already have other repeated assets, you just started noticing this one because jQuery made it evident.

This link helped me:

http://www.ruby.code-experiments.com/blog/2011/10/another-gotcha-with-the-rails-31-asset-pipeline-or-why-are-my-jquery-ujs-ajax-requests-triggered-twi.html



回答2:

make sure that you have submit buttons disabled after the click on them. it helps to localize the problem.

  $("form").submit(function(){
    $('input[type=submit]').attr('disabled', 'disabled');
  });


回答3:

I had the same problem on Rails 4. I had these settings in my development.rb:

config.assets.digest = true
config.assets.enabled = true

I deleted these and ran rake assets:clean

Now its submits like it should.



回答4:

On Rails 5, rails-ujs replaces jquery_ujs. Events will trigger twice if both are required

```

// app/assets/javascripts/application.js

//= require jquery_ujs <-- delete this

//= require rails-ujs

```