导入 - csv 到 activerecord - Rails 中的错误处理

发布于 2024-09-09 17:05:01 字数 418 浏览 4 评论 0原文

我正在编写一个导入例程,允许用户上传 CSV 文件来加载他们的数据库。 CSV 的每一行对应一个模型

我正在使用 FasterCSV 读取文件并将数据拆分为单独的模型,效果非常好。我只是无法确定处理错误的最佳方法。

现在我正在这样做,但对我来说这确实是错误的:

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

  return true
end

有没有更好的方法来保存模型集合?

I'm writing an import routine that will allow a user to upload a CSV file to load their database. Each row of the CSV corresponds to a model.

I'm using FasterCSV to read the file and split the data into individual models, which is working great. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

給妳壹絲溫柔 2024-09-16 17:05:01

当您想要追踪有问题的记录时,在循环中使用异常会给您带来各种麻烦。您可能会尝试将它们全部保存,但报告有错误的内容:

 def import(collection)
   failed = nil

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

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

   failed
 end

这假设您有兴趣查看错误。如果任何记录失败,它们将以数组形式返回。否则你会得到一个零,这意味着没有错误。

如果你不在乎,你总是可以进行快速而肮脏的保存:

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

这将在第一次失败时弹出 ActiveRecord::RecordInvalid 异常。

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.

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.

-柠檬树下少年和吉他 2024-09-16 17:05:01

对于这个问题,我认为更好的方法是你的。也许并非 csv 中的所有记录都经过验证,那些不经过验证的记录并不重要(记录它们以便了解错误)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文