Rails更新更高效

时间:2018-04-07 20:38:54

标签: ruby-on-rails-4

我需要每5分钟更新一次所有条目。我使用的是Rails版本4.2.5和Ruby版本2.3.0。我的代码在少量条目下运行良好。我现在有大约800个条目,最多需要2分钟才能更新。有更有效的方法吗?

  @players = Entry.all
  for player in @players
    sort = 0
    @player_selection = Selection.includes(:golfer).where("entry_id = ?", player.id).order('golfers.score asc').all
    for selection in @player_selection
      sort += 1
      score_sort = Selection.where("id = ?", selection.id).first
      score_sort.sort = sort
      score_sort.save
      player = Entry.where("id = ?", selection.entry_id).first
      player.score = Selection.includes(:golfer).where("entry_id = ? and selections.sort < 6", selection.entry_id).sum('golfers.score')
      player.save
    end
  end

谢谢。

1 个答案:

答案 0 :(得分:0)

在我看来,您可以将一些工作卸载到创建和/或更新记录时(而不是按计划汇总)。

e.g。类似的东西:

# I assume your relationship is something like this:

class Golfer
  belongs_to :entry
  after_create :update_scores
  after_update :update_scores

  private

  def update_scores
    entry.update(score: entry.golphers.sum(:score))
  end
end

这将减少运行排序更新过程时的工作量。 然后您的排序更新过程可以简化:

@entries = Entry.all
@entries.each do |entry|
  sort = 0
  @selections = Selection.includes(:golfer).where("entry_id = ?", player.id).order('golfers.score asc')
  @selections.each do |selection|
    sort += 1
    selection.update(sort: sort)
  end
end

通过删除无关的数据请求,这将略微改善操作。但是,您当前的操作最好是线性的,因为您将其作为循环运行:(O)n + 1运行时。您可能不得不放入SQL以获得更快的计算速度:

# -> SQL; depends on DB a bit
UPDATE selections s
s.sort = ns.new_sort
FROM 
(SELECT id, ROW_NUMBER() OVER (ORDER BY score ASC) AS new_sort 
from selection) as nt

您可以使用Rails运行纯SQL命令,如下所示:

# Be careful, this is dangerous
sql = "UPDATE ... your sql query here"
ActiveRecord::Base.connection.execute(sql)