简体   繁体   English

导入-CSV到ActiveRecord-Rails中的错误处理

[英]Import - csv to activerecord - error handling in Rails

I'm writing an import routine that will allow a user to upload a CSV file to load their database. 我正在编写一个导入例程,该例程将允许用户上传CSV文件以加载其数据库。 Each row of the CSV corresponds to a model . CSV的每一行都对应一个模型

I'm using FasterCSV to read the file and split the data into individual models, which is working great. 我正在使用FasterCSV读取文件并将数据拆分为单独的模型,效果很好。 I'm just having trouble deciding on the best approach to handle errors. 我只是在确定处理错误的最佳方法方面遇到困难。

Right now I have this going, but it really seems wrong to me: 现在我有这个打算,但是对我来说确实很不对劲:

def import(collection)
  begin
    self.transaction do
      collection.collect{|object| object.save!}
    end
  rescue ActiveRecord::RecordInvalid => invalid
    return false
  end

  return true
end

Is there a better way to save a collection of models? 有没有更好的方法来保存模型集合?

Using an exception in a loop is going to cause all kinds of headaches for you when you want to track down the problematic record. 当您要查找有问题的记录时,在循环中使用异常会为您带来各种麻烦。 What you might do is try and save them all, but report on those with errors: 您可能会尝试保存所有内容,但要报告有错误的内容:

 def import(collection)
   failed = nil

   transaction do
     failed = collection.reject { |r| r.save }

     unless (failed.empty?)
       raise ActiveRecord::Rollback
     end
   end

   failed
 end

This presumes you're interested in having a look at the errors. 假设您有兴趣查看这些错误。 If any records fail, they will be returned in an Array. 如果任何记录失败,它们将以数组形式返回。 Otherwise you'll get a nil, which means no errors. 否则,您将得到nil,这意味着没有错误。

If you don't care, you can always just do a quick and dirty save: 如果您不在乎,可以随时进行快速而肮脏的保存:

def import(collection)
  transaction do
    collection.each(&:save!)
  end
end

This will pop an ActiveRecord::RecordInvalid exception for the first failure. 对于第一次失败,这将弹出一个ActiveRecord :: RecordInvalid异常。

For this problem I think the better approach is yours. 对于这个问题,我认为更好的方法是您的方法。 Maybe not all the records in the csv aré going yo validare, and those that not doesnt matter (log them in order to know the errors) 也许不是csvaré中的所有记录都有效,而那些没关系的记录(记录它们以了解错误)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM