两个有比赛的球员的正确的铁轨关联是什么

时间:2014-12-08 04:57:03

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有“玩家”和“匹配”的模型。每场比赛记录有两名球员,一名获胜者和一名失败者。

对于这个有什么好的Rails Active Record关联?

Player
  name

Match
  winner_id (this is a player ID)
  loser_id (this is a player ID)

我希望能够获得一名球员的胜利数,并让所有从未参加比赛的球员获得胜利。

1 个答案:

答案 0 :(得分:1)

你可以做任何一件事

有一个

class Match < ActiveRecord::Base
  has_one :winner, class_name: "Player", foreign_key: "winner_id"
  has_one :loser, class_name: "Player", foreign_key: "loser_id"
end

或者,如果您想稍后更新哪个是赢家/输家,您可以执行类似

的操作

有很多通过

class Match < ActiveRecord::Base
  has_many :players, through: :match_players

  # Pseudocode - not sure if this is the exact query you'd need, given players relies on the table which is being JOINed
  def winner
    players.joins(match_players: {winner: true}).load.first
  end
end

你的MatchPlayers连接模型/表将定义一些标识赢家/输家的字段。

另一个选项有很多通过

class Match < ActiveRecord::Base
    # http://guides.rubyonrails.org/association_basics.html#options-for-has-many-source
    has_one :winner, through: :match_players, source: :player
    # etc.
end

您可以通过多种不同方式执行此操作,使用不同的关联和方法来保留所需的数据。

对于播放器型号,这取决于您对应用程序的需求。让我们假设你使用类似第三种选择的东西。球员协会可能看起来像

class Player < ActiveRecord::Base
    has_many :matches, through: :match_players
end

这是基本的关联设计,我建议您阅读我的答案底部的链接,因为您需要决定哪种解决方案(如果有的话)最适合您的使用案例。

您需要决定哪种类型的关联最适合您的使用案例。您可以在http://guides.rubyonrails.org/association_basics.html

了解详情