Rails:同一两个模型之间的多个Join表 [英] Rails: Multiple Join tables between the same two models

查看:183
本文介绍了Rails:同一两个模型之间的多个Join表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:Player和Event,参与者和课程之间有两个联接表。

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.

问题是,如果我要执行 @ player.events ,则结果查询将使用课程联接表

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?

编辑: 这是联接表模型:

class Lesson
    belongs_to :player
    belongs_to :event
end

class Participant
    belongs_to :player
    belongs_to :event
end


推荐答案

您可以使用class_name选项更改has_many关联之一的名称,但仍与另一个类关联。在我的示例中,我在事件学生用于玩家 >通过讲座事件 player 课程。但是你叫他们的名字可能有所不同。

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

这篇关于Rails:同一两个模型之间的多个Join表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆