我正在导入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
答案 0 :(得分:0)
这会破坏所有库存记录,而不仅仅是当前用户:
Inventory.destroy_all
相反,这将破坏属于当前用户的库存:
Inventory.where(user_id: user_id).destroy_all