2013-04-10 47 views
0

我有以下幾種,每個玩家有很多遊戲,每個遊戲都有很多玩家,玩家可以選擇去或不去遊戲。什麼是通過多對多關係屬性訪問的最佳方式?

Game 
has_many :shows 
has_many :players, :through => :shows 

Player 
has_many :shows 
has_many :games, :through => :shows 

Show Migration 
    t.references :game 
    t.references :player 
    t.boolean :going, :default => false 

我想要做的就是如果玩家決定去參加比賽,那麼最好的方法是什麼?

回答

1

假設你知道玩家(player_id)和特定遊戲(game_id)的id的id,你可以做到以下幾點:

Show.where('player_id = ? and game_id = ?', player_id, game_id).first.update_attributes(:going => true) 

這是更冗長,但可能太:

player = Player.find(player_id) 
show = player.shows.find_by_game_id(game_id) 
show.update_attributes(:going => true) 

如果你想遍歷遊戲中,你可以這樣做:

player = Player.find(id_of_player) 

player.shows.each do |show| 
    if show.game == ... # condition that decides whether player's going or not 
    show.update_attributes(:going => true) 
    end 
end 
相關問題