Shelby S
Shelby S

Reputation: 420

Dropzone on Rails causing double form submission to DB

When the "Save" button is clicked, there are two entries created. One with the :map information stored, and one missing it, both with same :name. How do I get only the complete entry to save?

new.html.erb

<%=form_for [@location, @floor], html: {class: "dropzone", multipart: true, id: "map-upload"} do |f|%>
  <div>
    <%=f.label :name%>
    <%=f.text_field :name%>
  </div>

  <div class="fallback">
    <%=f.label :map%>
    <%=f.file_field :map%>
  </div>

  <%=f.submit "Save", id: "floor-submit"%>
<%end%>

drag-drop.js

$(document).ready(function() {
  // disable auto discover
  Dropzone.autoDiscover = false;

  var mapUpload = new Dropzone("#map-upload", {
    paramName: "floor[map]",
    autoProcessQueue: false,
    maxFiles: 1,
    addRemoveLinks: false,
    dictDefaultMessage: 'Drag & drop a map image file here, or click here to select file to upload',
  });

  $('#map-upload').submit(function(e){
    mapUpload.processQueue();
  });
});

Relevant part of floor_controller:

  def create
    @floor = current_user.company.locations.find(params[:location_id]).floors.create(floor_params)

    if @floor.save
      flash[:notice] = "Floor has been created."
      redirect_to location_floors_path
    else
      flash[:alert] = "There was an error saving the floor, please try again"
      render 'new'
    end
  end

model

class Floor < ActiveRecord::Base
  belongs_to :location

  has_attached_file :map
  validates_attachment_content_type :map, :content_type => /\Aimage\/.*\Z/
end

Upvotes: 0

Views: 360

Answers (1)

Yifei W
Yifei W

Reputation: 101

I think your js is submitting it once and your rails form is submitting it the second time. Would recommend disabling one of them.

Upvotes: 1

Related Questions