Validate uniqueness when updating without aborting the update process while importing CSV Rails

51 views Asked by At

I have a database for managing staff in a large company. Each department is responsible for managing their own data. So I have Staff and Department models as shown below:

class Staff < ApplicationRecord
  belongs_to :department

  validates :national_id, presence: true,
    uniqueness: { scope: [:department_id] }  
end
class Department < ApplicationRecord
  has_many :staffs

end

It is possible for one staff to work in several departments. Therefore, when updating data, the system is supposed to check for the department and national_id of a staff and then proceed to update the data. That is why I am validating national_id with a scope on department_id. I have also enforced a uniqueness index on the staffs table as shown below:

class AddUniqueIndexToStaffs < ActiveRecord::Migration[5.1]
  def change
    add_index :staffs, [:national_id, :department_id], unique: true
  end
end

When it comes to importing the CSV, I have used the following method:

def load_imported_staffs
    spreadsheet = open_spreadsheet
    spreadsheet.default_sheet = 'Staff'
    header = spreadsheet.row(2)
    (3..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      staff = Staff.find_by(national_id:row["national_id"], department_id: row["department_name"]) || Staff.new
      staff.attributes = row.to_hash.slice("name", "national_id", "department_name")
      staff
    end
  end

Since staff can work in different departments, my idea is to find_by both national_id and department_id just to ensure that the wrong staff is not updated during import in case the same national_id is found in another department.

Here is my CSV:

enter image description here

When I am importing the CSV, the update aborts and I get the error:

Row : national_id has already been taken

for all the rows. The script is not able to update existing data . Where am I going wrong? I love rails but am a beginner and have spent hours on this and can't seem to get a way. Thanks in advance.

0

There are 0 answers