代码之家  ›  专栏  ›  技术社区  ›  Maher Manoubi

通过多对多关系的属性访问的最佳方式是什么?

  •  0
  • Maher Manoubi  · 技术社区  · 13 年前

    我有以下内容,每个玩家都有很多游戏,每个游戏都有很多玩家,玩家可以选择去或不去玩游戏。

    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 回复  |  直到 12 年前
        1
  •  1
  •   Mischa    13 年前

    假设你知道玩家的id( player_id )以及特定游戏的id( game_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