2019-10-21 05:52:44 -07:00

42 lines
1.3 KiB
Ruby

class Table < ActiveRecord::Base
#TODO has_many :moderators
has_many :seats
has_many :users, through: :seats
has_many :games
has_many :players, through: :games
#TODO: Deprecated current_game_id from database.
# Instead calculate with self.current_game
#
#has_one :current_game, :class_name => "Game", :primary_key => "current_game_id"
#TODO: Should these be part of Game initialize instead of callback?
after_create :add_seats
after_create :add_game
# Returns the newest joinable table or creates a new table if none are found
# scope :play_now, lambda { |user|
# where(status:nil).joins("LEFT OUTER JOIN players ON players.table_id = tables.id").group("tables.id").having("count(players) < 4").last || Table.create(title: "Game " + user.soft_token[0..4])
# }
scope :play_now, lambda { |user|
# where(status:nil).joins("LEFT OUTER JOIN players ON players.game_id = games.id").group("games.id").having("count(players) < 4").last || Table.create(title: "Game " + user.soft_token[0..4])
where(game:nil).last || Table.create(title: "Table " + user.soft_token[0..4])
}
def current_game
self.games.last
end
private
def add_seats
1.upto(4) do |i|
self.seats.create(position: i)
end
end
def add_game
self.games.create if self.current_game_id.blank?
end
end