bet.rb
1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#
class Bet < ApplicationRecord
  validates :score_visit, :score_local, :user_id, :match_id, 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