【问题标题】:Modeling a 2:n relationship effectively in Rails在 Rails 中有效地建模 2:n 关系
【发布时间】:2012-06-25 21:55:41
【问题描述】:

这是我得到的:

我有一个模型比赛和一个模型团队。一场比赛有 home_team 和 away_team。事实上,这是一个 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_id'

 public
 def matches
   return home_matches + away_matches
 end
end

class Match < ActiveRecord::Base
 attr_accessible :away_team_id, :home_team_id
 belongs_to :home_team, :class_name => 'Team', :foreign_key => 'home_team_id'
 belongs_to :away_team, :class_name => 'Team', :foreign_key => 'away_team_id'

结束

现在我可以有效地调用 Team.find(2).matches 并获得所有客场和主场比赛。但是我不喜欢的是它需要两个 SQL 查询而不是一个

SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2
SELECT `matches`.* FROM `matches` WHERE `matches`.`away_team_id` = 2

如何让 Rails 使用这个查询?

  SELECT `matches`.* FROM `matches` WHERE `matches`.`home_team_id` = 2 OR `matches`.`away_team_id` = 2

反之亦然,同样令人头疼;如果我定义一个方法team 合并home_teamaway_team,我会在只需要一次查询的情况下查询数据库两次。

【问题讨论】:

    标签: sql ruby-on-rails activerecord has-many belongs-to


    【解决方案1】:
    def matches
        Match.where("home_team_id = ? OR away_team_id = ?", id)
    end
    

    此外,您不需要 Match 模型中的那些外键。这些属性包含在 Match 模型本身中,因此不是外来的。

    【讨论】:

    • 哦,你是对的。外键是复制/粘贴错误...无论如何,我试图保持干净并使用内置的 ActiveRecord 关系来模拟该行为。但是您的解决方案至少在单个 SQL 查询(最重要的一点)方面有效......我希望我可以在 belongs_to 和 has_many 子句中包含选项。没办法?
    猜你喜欢
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多