我有一个比赛模型(即网球或乒乓球比赛)。它涉及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"
我也愿意接受关于如何构建模型的建议(即,如果player1/player2列不是最佳选择)。
请记住,每场比赛必须属于2名球员,而且只能属于2名。
这应该适用于您:
# 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