简体   繁体   English

在 Heroku 上运行长轨道控制台或 rake 任务

[英]Running a long rails console or rake task on Heroku

My rails application is hosted on Heroku.我的 rails 应用程序托管在 Heroku 上。 I'm trying to process data in my postgresql DB with a straightforward loop我正在尝试使用简单的循环处理我的 postgresql DB 中的数据

  DocumentText.all.each do |t|
    if is_number? t.src
      puts t.src
      t.targ = t.src
      t.save
    end
  end

The problem I have is my rails console will exit after running through some of my records (not all of them.) I have tried this as a rake task but same problem.我遇到的问题是我的rails控制台将在运行我的一些记录(不是全部)后退出。我已经尝试将其作为一个rake任务但同样的问题。

Why is this happening and what are my options?为什么会发生这种情况,我有什么选择?

In your code snippet, you are running n update queries to the database which will take a lot of time and this is why your task is not fully running.在您的代码片段中,您正在对数据库运行 n 个更新查询,这将花费大量时间,这就是您的任务未完全运行的原因。

I would suggest running a single update query to the database.我建议对数据库运行单个更新查询。 For that, add the following gem in your Gemfile为此,在您的 Gemfile 中添加以下 gem

gem 'activerecord-import'

documents = []
DocumentText.all.each do |t|
  documents << t if is_number?(t.src)
end


# MySQL version
DocumentText.import(documents, on_duplicate_key_update: {targ: :src})

# PostgreSQL version (no shorthand version)
DocumentText.import([book], on_duplicate_key_update: {
  conflict_target: [:id], columns: {targ: :src}
})

This should do the trick.这应该可以解决问题。 If you have data in millions, then I would also recommend running this process in batches.如果您有数百万的数据,那么我还建议您分批运行此过程。 Let me know if you need help with that.如果您需要帮助,请告诉我。

@Pradeep Agrawal's answer lead me to the solution using activerecord-import gem (his answer was copy and pasted from the gem and contained bugs). @Pradeep Agrawal 的回答让我找到了使用 activerecord-import gem 的解决方案(他的回答是从 gem 复制和粘贴并包含错误)。

documents = []
DocumentText.all.each do |t|
  if is_number?(t.src)
    documents << t
  end
end

DocumentText.import(documents, on_duplicate_key_update: {
  conflict_target: [:id], columns: {targ: :src}
})

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

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