【发布时间】:2021-06-26 18:55:21
【问题描述】:
所以我有三个模型,用户、团队和游戏。目前是这样构建的。
class Team < ApplicationRecord
has_and_belongs_to_many :users
has_many :home_games, class_name: 'Game', foreign_key: 'home_team_id'
has_many :away_games, class_name: 'Game', foreign_key: 'away_team_id'
has_many :wins, class_name: 'Game', foreign_key: 'winner_id'
belongs_to :owner, class_name: 'User'
end
class User < ApplicationRecord
has_and_belongs_to_many :teams
has_many :teams_owned, class_name: 'Team', foreign_key: 'owner_id'
has_many :games, through: :teams
end
class Game < ApplicationRecord
belongs_to :home_team, class_name: "Team"
belongs_to :away_team, class_name: "Team"
belongs_to :winner, class_name: "Team", optional: true
end
我想在用户和游戏之间添加关联。所以我可以调用 User.games 和 Game.users。
我尝试添加这个:
#in user model
has_many :games, through: :teams
#in team model
has_many :games, ->(team) { where('home_team_id = ? or away_team_id = ?', team.id, team.id) }, class_name: 'Game'
正如api docs 所说的那样。但是,当我尝试调用此关联时,我收到“game.team_id 不存在”的错误消息。因为每场比赛都有 home_team_id 和 away_team_id,但没有 team_id。
我只是执行得非常糟糕吗?还是我错过了什么?任何帮助表示赞赏。
【问题讨论】:
-
哪一行出现错误?
-
@JoelBlum 当我尝试调用 User.games 时
标签: ruby-on-rails