0
我正在導入CSV數據,但是我想首先刪除所有當前用戶數據,然後導入。有效地用新上傳的數據替換所有當前用戶數據..我無法弄清楚,任何幫助,非常感謝。import 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
只需稍加說明:如果庫存總是爲單個用戶導入,那麼'import'應該是'User'類的實例方法,而不是'Inventory'上的類方法。另外,它是'Inventory'還是'InventoryItem'? –