mb_s88
mb_s88

Reputation: 392

Using includes on a custom association in rails

I have a class Team that has many 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. 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?

Upvotes: 1

Views: 1233

Answers (1)

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

Like Sean Huber said, include the home and away matchups, then refer to them with .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.

Upvotes: 2

Related Questions