49 lines
1.4 KiB
Ruby

class Table < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
#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: user.soft_token[0..4])
}
def user_count
self.seats.map{|s| s.occupied? ? s : nil}.compact.count
end
def current_game
self.games.last
end
def add_game
self.games.create
end
private
def add_seats
1.upto(4) do |i|
self.seats.create(position: i)
end
end
end