Rails:跟踪每个级别的最高分的策略

时间:2014-03-24 04:41:47

标签: ruby-on-rails activerecord data-integrity after-save

我正在使用Rails应用,该应用需要跟踪用户所播放的每个级别得分最高

某个级别的每次尝试都有多个轮次,尝试中每轮的得分总和会被缓存为尝试中的total_score。

型号:

  • 高分(belongs_to:用户,级别,尝试)
  • 等级(has_many:尝试)
  • 尝试(has_many:rounds,belongs_to:user,level)
  • 回合(belongs_to:尝试)
  • 用户(has_many:high_scores,尝试次数)

当更新中保存一轮时,它所属的尝试的total_score。我目前正在使用以下天真的实现,但计划尽快重构。在我重构之前,我想知道是否有更好的策略来保持这些信息的最新状态。

def update_high_score_if_needed
  high_score = HighScore.where(user_id: self.user_id, level_id: self.level_id).first
  if high_score.nil?
    high_score = HighScore.create(attempt_id: self.id, level_id: self.level_id, user_id: self.user_id, score: self.total_score)
  else
    if high_score.score < self.total_score
      high_score.update_attributes(attempt: self, score: self.total_score)
      self.update_attribute(:was_high_score, true)
    else
      record_attempt = self.user.attempts.where(level_id: self.level_id).order('total_score DESC').first
      if record_attempt.nil?
        high_score.destroy
      else
        high_score.update_attributes(attempt: record_attempt, score: record_attempt.total_score)
      end
    end
  end
end

我知道我可以查询这些信息,但是当我想要显示所有高分时我想要快速响应,并且如果每次尝试都很高,我希望能够存储在完成时得分。

0 个答案:

没有答案
相关问题