title: Rails CSV Import Duplicating Records
body: <p>I've managed to get CSV imports working (based on <a href="https://github.com/RichIsOnRails/CSVImportExample" rel="nofollow">this repo</a>) on a Rails 4 app. The issue is that on my development system, the imports appear to work correctly, but in production, all records get duplicated. See existing code below. Any ideas what could be causing the duplication? All records appear in the CSV once only, all have blank ID columns since I want the system to assign the assigns.</p>
  
  <p>books_controller.rb</p>
  
  <pre><code>def import
      begin
        Book.import(params[:file])
        redirect_to root_url, notice: "Books imported."
      rescue
       redirect_to root_url, notice: "Invalid CSV file format."
      end
  end
  
  def create
    @book = Book.new(book_params)
    @book.save
    save_previews(params[:previews])
    respond_with(@book)
  end
  
  def save_previews images
    if images
      images.each_value { |image|
      @book.previews.create(image: image)
      }
    end
  end
  </code></pre>
  
  <p>book.rb</p>
  
  <pre><code>def self.import(file)
    CSV.foreach(file.path, headers: true, :encoding =&gt; 'utf-8') do |row|
  
      product_hash = row.to_hash
      product = Book.where(id: product_hash["id"])
  
      if product.count == 1
        product.first.update_attributes(product_hash)
      else
        Book.create!(product_hash)
      end # end if !product.nil?
    end # end CSV.foreach
  end # end self.import(file)
  </code></pre>
  
  <p>routes.rb</p>
  
  <pre><code>resources :books do
      get "books/:page", :action =&gt; :index, :on =&gt; :collection
      resources :comments
      collection do 
        post :import
      end
  end
  </code></pre>
  
  <p>users#show.html.erb</p>
  
  <pre><code>&lt;% if user_signed_in? &amp;&amp; current_user.super_admin? %&gt;
    &lt;%= form_tag import_books_path, multipart: true do %&gt;
      &lt;div class="form-group"&gt;
        &lt;%= file_field_tag :file %&gt;
        &lt;%= submit_tag "Import CSV", class: "form-control" %&gt;
      &lt;/div&gt;
    &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>