Sql 在Rails中有效地建模2:n关系
以下是我得到的: 我有一个模特比赛和一个模特队。比赛分主队和客队。事实上,这是一种2:n的关系Sql 在Rails中有效地建模2:n关系,sql,ruby-on-rails,activerecord,has-many,belongs-to,Sql,Ruby On Rails,Activerecord,Has Many,Belongs To,以下是我得到的: 我有一个模特比赛和一个模特队。比赛分主队和客队。事实上,这是一种2:n的关系 class Team < ActiveRecord::Base has_many :home_matches, :class_name => 'Match', :foreign_key => 'home_team_id' has_many :away_matches, :class_name => 'Match', :foreign_key => 'away_team
class Team < ActiveRecord::Base
has_many :home_matches, :class_name => 'Match', :foreign_key => 'home_team_id'
has_many :away_matches, :class_name => 'Match', :foreign_key => 'away_team_id'
public
def matches
return home_matches + away_matches
end
end
如何让Rails使用此查询
SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2 OR `matches`.`away_team_id` = 2
反之,同样的头痛;如果我定义了一个方法team
,该方法将home\u team
和away\u team
合并在一起,我将在只需要一个查询的情况下查询数据库两次
def matches
Match.where("home_team_id = ? OR away_team_id = ?", id)
end
此外,在匹配模型中不需要这些外键。这些属性包含在匹配模型本身中,因此不是外来属性。哦,你说得对。外键是复制/粘贴错误…无论如何,我试图保持干净,并使用内置的ActiveRecord关系来建模该行为。但您的解决方案至少在单个SQL查询方面有效(最重要的一点)。。。我希望我的选择能包括在属于并且有很多条款的条款中。不行?
SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2 OR `matches`.`away_team_id` = 2
def matches
Match.where("home_team_id = ? OR away_team_id = ?", id)
end