add additional database table connecting game matches to participating players

This commit is contained in:
2026-11-10 01:04:07 +03:00
parent 271daac935
commit 219448ccfb
10 changed files with 103 additions and 3 deletions
+9
View File
@@ -2,6 +2,9 @@ class Match < ApplicationRecord
belongs_to :player1, class_name: "User"
belongs_to :player2, class_name: "User"
has_many :match_players, foreign_key: :match_uuid, primary_key: :uuid, dependent: :destroy, inverse_of: :match
has_many :players, through: :match_players, source: :player
enum :status, {
ongoing: 0,
player1_won: 1,
@@ -11,6 +14,7 @@ class Match < ApplicationRecord
}
before_validation :assign_uuid, on: :create
after_create :create_match_players!
validates :uuid, presence: true, uniqueness: true
validates :status, presence: true
@@ -40,4 +44,9 @@ class Match < ApplicationRecord
errors.add(:player2, "must differ from player1")
end
end
def create_match_players!
match_players.create!(player: player1)
match_players.create!(player: player2)
end
end
+8
View File
@@ -0,0 +1,8 @@
class MatchPlayer < ApplicationRecord
belongs_to :match, foreign_key: :match_uuid, primary_key: :uuid, inverse_of: :match_players
belongs_to :player, class_name: "User", foreign_key: :player_id, inverse_of: :match_players
validates :match_uuid, presence: true
validates :player_id, presence: true
validates :player_id, uniqueness: { scope: :match_uuid }
end
+2
View File
@@ -4,6 +4,8 @@ class User < ApplicationRecord
has_many :sessions, dependent: :destroy
has_many :matches_as_player1, class_name: "Match", foreign_key: :player1_id, dependent: :restrict_with_exception, inverse_of: :player1
has_many :matches_as_player2, class_name: "Match", foreign_key: :player2_id, dependent: :restrict_with_exception, inverse_of: :player2
has_many :match_players, foreign_key: :player_id, dependent: :destroy, inverse_of: :player
has_many :matches, through: :match_players, source: :match
has_one_attached :avatar
normalizes :nickname, with: ->(n) { n.strip }