2013-04-10 102 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 
相关问题