您绝对不应该删除所有记录,然后从数据中重新创建它们。这将产生各种问题,例如破坏其他表中的任何外键字段,这些字段在删除之前指向对象。这就像为了拥有一扇不同颜色的门而将一所房子推倒并重建它。因此,“查看它是否存在,如果存在则更新它(如果它不同),如果不存在则创建它”是正确的使用策略。
你没有说你的删除标准是什么,但如果它是“应该删除导入数据中未提及的任何记录”,那么你只需要跟踪输入数据中的一些唯一字段,然后删除其唯一字段不在该列表中的所有记录。
因此,您进行导入的代码可能看起来像这样(从另一个问题复制代码:此代码以非常笨拙的方式设置数据,但我不打算在这里解决)
namespace :data do
desc "import data from files to database"
task :import => :environment do
file = File.open(<file to import>)
identifiers = []
file.each do |line|
#disclaimer: this way of setting the data from attrs[0], attrs[1] etc is crappy and fragile and is not how i would do it
attrs = line.split(":")
identifier = attrs[0]
identifiers << identifier
if p = Product.find_or_initialize_by_identifier(identifier)
p.name = attrs[1]
etc...
p.save!
end
end
#destroy any which didn't appear in the import data
Product.where("identifier not in (?)", identifiers).each(&:destroy)
end
end