import csv删除所有现有记录,然后导入



我正在导入CSV数据,但我想先删除所有当前用户的数据,然后再导入。有效地用新上传的数据替换所有当前用户数据。。我想不通,我们非常感谢您的帮助。

这是我所拥有的,但不起作用:(它删除了所有用户数据,而不仅仅是当前用户数据。)删除了整个库存表,而不是带有current_user.id 的行

class Inventory < ApplicationRecord
    belongs_to :user
def self.import(file, user_id)
  Inventory.destroy_all
  allowed_attributes = [ "user_id", "id","description","part_number","price","created_at","updated_at", "alternate_part_number", "condition_code", "qty", "mfg_code", "serial_number", "part_comments"]
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    inventory = find_by_id(row["id"]) || new
    inventory.attributes = row.to_hash.select { |k,v| allowed_attributes.include? k }
    inventory.user_id = user_id
    inventory.save!
  end
end

这将销毁所有库存记录,而不仅仅是当前用户的:

Inventory.destroy_all

相反,这将销毁属于当前用户的库存:

Inventory.where(user_id: user_id).destroy_all

最新更新