0

My problem is that i have to export an excel sheet save some rows to the database without duplication or redundancy so i started it with importing CSV instead of XLS then when i finish i might be able to parse the xls this is my model code:

require 'csv'
class Machine < ActiveRecord::Base
  def self.assign_row(row)
  a, b, c, d = row
  @c = c.slice(1,4)
 Machine.create(name: c, mid: @c)
   end
 def self.import(file)
 CSV.foreach(file.path) do |row|
  machine = Machine.assign_row(row)
    end
  end
 end     

Import method in machines_controller

 def import
 count = Machine.import params[:file]
 redirect_to machines_path, notice: "file imported successfully!"
  end     

Migration code

 def change
 create_table :machines do |t|
 t.string :name
 t.string :mid
 t.timestamps null: false
 end
  add_index :machines, :name, :unique => true
 end     

and the view code

 <%= form_tag import_machines_path, multipart: true do %>
 <%= file_field_tag :file %>
 <%= submit_tag "upload" %>
 <% end %>    

routes

  Rails.application.routes.draw do
 resources :errors
 resources :machines do
  collection do
     post :import
    end
   end
  root "machines#index
   end         

any thoughts on how to skip duplicated records from saving into database would be appreciated thanks

1 Answer 1

1

Unique Identifier: To avoid duplicate records saving to database you should maintain a unique identifier other than primary key. This helps you to identify if the record already available in DB, if it is available you can skip that record from saving again.

I guess you can use name in this case, which should be unique for each record in database. write a uniqueness validation in model to implement this.

After changes:

 validates_uniqueness_of  :name

 def self.assign_row(row)
   a, b, c, d = row
   @c = c.slice(1,4)
   machine = Machine.find_by(name: c)
   Machine.create(name: c, mid: @c) if machine.blank?
 end

Hope it helps!! Thank you.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your response i did that however i got this error NoMethodError in MachinesController#import undefined method `import' for #<Class:0x007fcb7c171638>
In your controller, change the line count = Machine.import params[:file] to count = Machine.import(params[:file])
I have edited my answer as you have defined name as unique in your migration. Please check
Thank you , you had saved me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.