简体   繁体   English

在Rails中的自定义关联上使用包含

[英]Using includes on a custom association in rails

I have a class Team that has many Matchups 我有一个类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

and

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

This all works fine, until I want to use includes like this: Team.includes(:matchups) because although matchups returns an active record relation I can't use it. 所有这些Team.includes(:matchups) ,直到我要使用includes以下内容的项: Team.includes(:matchups)因为尽管matchups返回了活动记录关系,但我无法使用它。 This is a problem later because I need this kind of information for many teams and I don't want to make a query for every team. 稍后会出现问题,因为我需要许多团队使用这种信息,而我不想对每个团队都进行查询。 Can anyone tell me how I could use includes to get the combination? 谁能告诉我如何使用包含来获得组合?

Like Sean Huber said, include the home and away matchups, then refer to them with .matchups 就像肖恩·胡伯(Sean Huber)所说的那样,包括主场和客场对决,然后用.matchups

def matchups
  (home_matchups + away_matchups).sort_by(&:week)
end

It's a little slower (maybe), but you'll be guaranteed to use the relation if it's loaded. (也许)有点慢,但是如果已加载关系,则可以保证使用。

The general approach here - include the relations like you would, then use convenience methods that refer to those relations - whether it's in a view or another model method like this example. 此处的通用方法-像您一样包含关系,然后使用引用这些关系的便捷方法-无论是在视图中还是在本示例中的其他模型方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM