1

私は、ユーザーがプレイする各レベルの最高スコアを追跡する必要がある Rails アプリに取り組んでいます。

レベルの各試行には複数のラウンドがあり、試行の各ラウンドのスコアの合計が試行の total_score としてキャッシュされます。

モデル:

  • ハイスコ​​ア (belongs_to: ユーザー、レベル、試行)
  • レベル (has_many: 試行回数)
  • 試行 (has_many: ラウンド、begs_to: ユーザー、レベル)
  • ラウンド (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

この情報を照会するだけでよいことはわかっていますが、すべてのハイスコアを表示したい場合は迅速な応答が必要であり、各試行がその時点でハイスコアであったかどうかを保存できるようにしたいと考えています。完了しました。

4

0 に答える 0