bet.rb 825 Bytes
#
class Bet < ApplicationRecord
  validates :score_local, :score_visit, presence: true
  belongs_to :user, inverse_of: :bets
  belongs_to :match, inverse_of: :bets
  enum result: [:visit, :tie, :local]

  scope :active, -> { joins(match: :pool).where(pools: { active: true }) }
  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 local_score == visit_score
    return :local if local_score > visit_score
    :visit
  end
end