如何通过外键列创建属于用户的ActiveRecord关系

时间:2013-11-26 18:37:14

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

我有一个比赛模特(比赛即网球或乒乓球比赛)。它涉及2个玩家(player1,player2),我希望我的user.matches能够在player1和player2之间返回用户的实例。

我所拥有的系统如下所示,但它似乎很笨拙且不直观:

用户模特:

has_many :matches, :foreign_key => "player1_id"
 has_many :reverse_matches, :foreign_key => "player2_id", :class_name => "Match"

匹配模型:

belongs_to :player1, :foreign_key => "player1_id", :class_name => "User"
  belongs_to :player2, :foreign_key => "player2_id", :class_name => "User"

我愿意接受有关如何构建模型的建议(例如,如果播放器1 /播放器2列不是可行的话)。

记住每场比赛必须属于2名且只有2名球员。

1 个答案:

答案 0 :(得分:1)

这应该适合你:

# User model
class User < ActiveRecord::Base
  has_many :home_matches, foreign_key: 'player1_id', class_name: 'Match' # if player1_id so he played at home
  has_many :away_matches, foreign_key: 'player2_id', class_name: 'Match' # if player2_id so he played to the other player's place

  def all_matches
    Match.where('player1_id = :user_id OR player2_id = :user_id', user_id: self.id)
  end

# Match model
class Match < ActiveRecord::Base
  belongs_to :home_player, foreign_key: 'player1_id', class_name: 'User'
  belongs_to :away_player, foreign_key: 'player2_id', class_name: 'User'

  def players
    User.where(id: [self.player1_id, self.player2_id])
  end


# usage
user = User.first
user.all_match # => returns the list of all played matches
user.home_matches # => returns the matches where this user was referenced as player1
user.away_matches # => returns the matches where this user was referenced as player2

match = Match.first
match.players # => returns the two players
match.home_player # => returns the player1