bet.rb 1.05 KB
#
class Bet < ApplicationRecord
  validates :visit, :local, :date, presence: true
  belongs_to :user, inverse_of: :bets
  belongs_to :match, inverse_of: :bets
  has_one :group, through: :user, inverse_of: :bets
  enum result: [:visit, :tie, :local]

  scope :active, -> { joins(match: :pool).where(pools: { active: true }) }
  scope :for_pool, -> (pool_id) { joins(:match).where(matches: { pool_id: pool_id } ) }
  scope :board, (lambda do
    joins(:user)
    .group('users.name')
    .order('sum_points')
    .sum(:points)
  end)

  before_save :assign_result

  def calculate
    return unless match.result
    update_column :points, calculate_result
  end

  def calculate_result
    return 5 if final_score_is_equal
    return 3 if result == match.result
    0
  end

  def assign_result
    self.result = find_result
  end

  private

  def final_score_is_equal
    match.score_local == score_local && match.score_visit == score_visit
  end

  def find_result
    return :tie if score_local == score_visit
    return :local if score_local > score_visit
    :visit
  end
end