【问题标题】:Rails: Active Record TimeoutRails:活动记录超时
【发布时间】:2017-06-15 07:15:54
【问题描述】:

这是一段代码。当我使用timeout 将它添加到 cron 时,整个数组将被保存两次。当我删除超时时,什么都没有保存

在这种情况下,我们希望将超过 10 万条记录的数组结果(来自 api)保存到数据库中。我在这里使用了批量插入和 TinyTds gems

ActiveRecord::Base.establish_connection(adapter: 'sqlserver', host: "xxx", username: "xxx", password: "xxx", database: "xxx", azure: true, port: 1433, timeout: 5000)

class Report < ActiveRecord::Base
  self.primary_key = 'id'
end

my_array = [] #count of 100000 records
Report.bulk_insert(:account_owner_id) do |worker|
  my_array.drop(2).each do |arr|
    worker.add account_owner_id: arr[0]
  end
end

【问题讨论】:

  • 请问您是如何触发此代码的?它来自控制器吗?是否会发生同样的情况是您从脚本运行它吗?您是否有机会将架构和数据文件发布到某处 - 或至少是数据文件的一部分。
  • 我从脚本运行它。这是我运行的代码。除此之外,我还有一个将数据填充到 my_array 的 api。向活动记录连接添加超时是否存在问题。当我使用 cron 运行代码时会发生此问题。有两个访问数据库的脚本,它们都有相同的代码

标签: ruby-on-rails tiny-tds


【解决方案1】:

您可以尝试删除timeout 并将ignore: true 添加到您的批量插入中,如here 所示。可能有插入失败。

Report.bulk_insert(:account_owner_id, ignore: true) do |worker|

【讨论】:

  • Ignore 会停止插入批次 - 但在我的情况下,它会保存批次 x 次。
  • 如果一条记录失败则继续。来自文档:The ignore option ignores the inserts that would have failed (because of duplicate keys or a null in column with a not null constraint) and inserts the rest of the batch.
猜你喜欢
  • 1970-01-01
  • 2013-02-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多