【问题标题】:import csv delete all existing records then import导入 csv 删除所有现有记录然后导入
【发布时间】:2016-11-24 12:00:57
【问题描述】:

我正在导入 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

标签: ruby csv import


【解决方案1】:

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

Inventory.destroy_all

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

Inventory.where(user_id: user_id).destroy_all

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2016-04-24
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多