Nathan Lauer
Nathan Lauer

Reputation: 391

Rails model that includes both a has_many and has_one relationship, relating two models that have a has_many to has_many relationship

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"

Upvotes: 0

Views: 177

Answers (1)

Iob
Iob

Reputation: 114

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

Upvotes: 0

Related Questions