0

直截了当:我的应用中有 Game、Board 和 Player 模型。

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

我没有看到任何我可以使用的开箱即用的东西。一个想法是使用验证,但这是唯一的方法吗?

4

2 回答 2

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"]
于 2013-08-25T18:21:00.123 回答
0

除了验证之外,您还可以使用自定义方法来添加子对象:

def add_player(player)
  if players.count < 2
    self.players << player
  else
    raise 'Too many players'
  end
end

这在使用此方法添加玩家时确实会强制执行限制,但在通过关联直接访问时不会强制执行限制,例如obj.players << player.

于 2013-08-25T17:53:49.873 回答