Q:

Rails CSV Import Duplicating Records

I've managed to get CSV imports working (based on this repo) 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.
books_controller.rb
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

book.rb
def self.import(file)
  CSV.foreach(file.path, headers: true, :encoding => '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)

routes.rb
resources :books do
    get "books/:page", :action => :index, :on => :collection
    resources :comments
    collection do 
      post :import
    end
end

users#show.html.erb
<% if user_signed_in? && current_user.super_admin? %>
  <%= form_tag import_books_path, multipart: true do %>
    <div class="form-group">
      <%= file_field_tag :file %>
      <%= submit_tag "Import CSV", class: "form-control" %>
    </div>
  <% end %>
<% end %>

A:

You want to use active record validations to make sure that you get no duplicates. This would be the uniqueness validation to make sure that there is only one record with that attribute. You will want a scope on that attribute to tie all of the other attributes together.
Here is a simple example: 
class Book < ActiveRecord::Base
  validates_uniqueness_of :title, scope: :product_id
end

