2013-08-25 63 views
0

直接主題:我在我的應用程序中有遊戲,棋盤和玩家模型。如何限制Rails協會的數量

Game -> Board <- Player 

對玩家的遊戲是通過棋盤多對多的關係。我想限制這個遊戲只能有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 

我沒有看到任何開箱即用的東西。一個想法是使用驗證,但這是唯一的方法嗎?

回答

3

假設你使用ActiveRecord或其他任何東西使用的ActiveSupport,你可以在董事會增加一個自定義的驗證:

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"] 
0

此外驗證,你也可以使用添加子對象的自定義方法:

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

這確實使用此方法添加球員,當執行限制,而不是在通過協會,如直接訪問obj.players << player