直接主题:我的应用程序中有游戏,棋盘和玩家模型。
Game -> Board <- Player
通过Boards,玩家的游戏是多对多的关系。我想限制游戏只能有2个棋盘(因此只有两个玩家)。
game = Game.create
game.players.push Player.create
game.players.push Player.create
game.players.push Player.create #this line should throw some exception
我没有看到任何可以使用的开箱即用的东西。一个想法是使用验证,但这是唯一的方法吗?
答案 0 :(得分:3)
假设您使用ActiveRecord或使用ActiveSupport的其他任何东西,您可以在Board上添加自定义验证:
class Board
validate :player_count_validation
has_many :players
private
def player_count_validation
if players.length > 2
errors.add(:players, "must have length at most two")
end
end
end
然后就会这样:
board = Board.new
board.players << Player.create!
board.players << Player.create!
board.players << Player.create! # No exception here
board.save # returns false
board.save! # Raises validation exception
board.errors # Something like { players: ["must have length at most two"] }
board.errors.full_messages # ["Players must have length at most two"]
答案 1 :(得分:0)
除了验证之外,您还可以使用自定义方法添加子对象:
def add_player(player)
if players.count < 2
self.players << player
else
raise 'Too many players'
end
end
这在使用此方法添加玩家时强制执行限制,但在通过关联直接访问时不会强制执行限制,例如obj.players << player
。