我的课程Team
有很多Matchups
class Team < ActiveRecord::Base
has_many(
:home_matchups,
class_name: "Matchup",
foreign_key: :team_1_id,
primary_key: :id
)
has_many(
:away_matchups,
class_name: "Matchup",
foreign_key: :team_2_id,
primary_key: :id
)
def matchups
Matchup.where("team_1_id = ? OR team_2_id = ?", id, id)
end
end
和
class Matchup < ActiveRecord::Base
validates :team_1_id, :team_2_id, :week, presence: true
belongs_to(
:team_1,
class_name: "Team",
foreign_key: :team_1_id,
primary_key: :id
)
belongs_to(
:team_2,
class_name: "Team",
foreign_key: :team_2_id,
primary_key: :id
)
has_one :league, through: :team_1, source: :league
end
这一切都运行正常,直到我想使用includes
这样:Team.includes(:matchups)
因为虽然matchups返回一个有效的记录关系,但我无法使用它。这是一个问题,因为我需要为许多团队提供此类信息,而且我不想为每个团队进行查询。任何人都可以告诉我如何使用包含来获得组合吗?
答案 0 :(得分:2)
就像肖恩·胡贝尔所说,包括本垒打和客场对决,然后用.matchups
def matchups
(home_matchups + away_matchups).sort_by(&:week)
end
它有点慢(也许),但如果它被加载,你将保证使用该关系。
这里的一般方法 - 包括你想要的关系,然后使用引用这些关系的便捷方法 - 无论是在视图中还是在这个例子中的其他模型方法。