【问题标题】:Rails - How to set up a relationship where has_many through could be multiple columnsRails - 如何建立has_many through可能是多列的关系
【发布时间】:2021-07-30 13:41:37
【问题描述】:
我已经离开 Rails 开发世界一段时间了,在设置表之间的关系和连接时有点生疏,如果这是一个非常简单的问题,请道歉。
- 我有一个
Team 模型,它有一个 id 列。
- 我有一个
Match 模型,它有home_team_id 和away_team_id
列。
- 我希望能够致电
@team.matches 并有任何Match
其中home_team_id 或away_team_id 等于
@team.id 出现。
我可以通过以下查询来实现它,但它远非理想。
@matches = Match.where(home_team_id: @team.id) || Match.where(away_team_id: @team.id))
那么,设置模型和关系以实现上述行为的推荐方法是什么?
提前致谢!
【问题讨论】:
标签:
ruby-on-rails
rails-activerecord
【解决方案1】:
这受到@Joel_Blum 的回答的启发。我认为它更简洁一些,并通过 home_matches 和 away_matches 范围扩展了实用程序:
class Match < ApplicationRecord
belongs_to :home_team, class_name: "Team"
belongs_to :away_team, class_name: "Team"
end
class Team < ApplicationRecord
has_many :home_matches, foreign_key: :home_team_id, class_name: "Match"
has_many :away_matches, foreign_key: :away_team_id, class_name: "Match"
def matches
home_matches.or(away_matches)
end
end
【解决方案2】:
这是一个可能的模型设置
class Match < ApplicationRecord
belogns_to :home_team, class_name: "Team"
belongs_to :away_team, class_name: "Team"
end
class Team < ApplicationRecord
has_many :matches,-> {
unscope(:where).where(home_team_id: self.id).or(where(away_team_id: self.id))
}
end
现在@team.matches 应该可以工作了。唯一棘手的部分是让 has_many 工作with 2 foreign keys by doing unscope(:where)
【解决方案3】:
我在模型中做了类似的事情:
def matches
Match.where('home_team_id = ? OR away_team_id = ?', self.id, self.id)
end
这至少给了你一个范围。然后在你的控制器中:
@matches = @team.matches
我会对任何其他想法感兴趣。