user8199214
user8199214

Reputation:

Rails: Multiple Join tables between the same two models

I have two models: Player and Event with two join tables between them, participants and lessons.

class Event
    has_many :participants
    has_many :players, through: :participants

    has_many :lessons
    has_many :players, through: :lessons
end

class Player
    has_many :participants
    has_many :events, through: :participants

    has_many :lessons
    has_many :events, through: lessons
end

Not all events have lessons but all events have participants hence why I split the join table into two.

The problem is that if I were to do @player.events the resulting query would use the lessons join table instead of the participants.

Is there a better way to do this this?

EDIT: Here are the join table models:

class Lesson
    belongs_to :player
    belongs_to :event
end

class Participant
    belongs_to :player
    belongs_to :event
end

Upvotes: 1

Views: 1268

Answers (1)

Michael Gorman
Michael Gorman

Reputation: 1077

You can use the class_name option to change the name of one of the has_many associations but still associate with the other class. In my example I am using students for players on an event through lessons, and lectures for events on a player through lessons. But what you name them can be different.

class Event
    has_many :participants
    has_many :players, through: :participants

    has_many :lessons
    has_many :students, through: :lessons, class_name: "Player"
end

class Player
    has_many :participants
    has_many :events, through: :participants

    has_many :lessons
    has_many :lectures, through: lessons, class_name: "Event"
end

Upvotes: 1

Related Questions