0

This is a slight extension of this question: Rails model that has both 'has_one' and 'has_many' but with some contraints

Here, I am trying to relate two models that each has_many of the other -> I have an in between model which stores the foreign keys, allowing for a "through" relationship. Specifically, I'm trying to relate matchups and teams, and I'd like for each team to "has_one :current_matchup"

Here are the relevant excerpts from my models:

Team:

has_many :matchup_teams
has_many :matchups, through: :matchup_teams

Matchup:

has_many :matchup_teams
has_many :teams, through: :matchup_teams

MatchupTeam:

belongs_to :matchup
belongs_to :team

How can I do this? Here is my current attempt, which causes an error:

Model Team:

has_one  :current_matchup_team, -> { where(is_current: true) }, :class_name=> "MatchupTeam"
has_one :current_matchup, through: :current_matchup_team, :class_name=>"Matchup"
Nathan Lauer
  • 381
  • 5
  • 18

1 Answers1

0

It would be a better aproach if you use a method instead of an association to retrieve the current_matchup:

Model: Team

def current_matchup
    matchups. where(is_current: true) 
end
Iob
  • 114
  • 10
  • Ok, I'm happy to do that - can I use that method in an eager_load statement? For example, user.teams.includes(:current_matchup), or something like that? – Nathan Lauer Jun 15 '17 at 16:42
  • Unfortunately it doesn't work, it has to be a model relationship. – Iob Jun 15 '17 at 16:53
  • ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) "current_matchup" or :current_matchup in model LeaguesAndTeams::MatchupTeam. Try 'has_many :current_matchup, :through => :current_matchup_team, :source => '. Is it one of matchup or team? – Nathan Lauer Jun 15 '17 at 16:56
  • I removed the namespaces in my question above for brevity – Nathan Lauer Jun 15 '17 at 16:56