我有两个模型:玩家和事件,它们之间有两个连接表、参与者和课程。
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
并非所有事件都有课程,但所有事件都有参与者,因此我将连接表分成两部分。
问题是如果我这样做@player.events
生成的查询将使用课程连接表而不是参与者。
有没有更好的方法来做到这一点?
EDIT:以下是连接表模型:
class Lesson
belongs_to :player
belongs_to :event
end
class Participant
belongs_to :player
belongs_to :event
end
您可以使用 class_name 选项更改 has_many 关联之一的名称,但仍与另一个类关联。在我的例子中我使用students
for players
on an event
通过lessons
, and lectures
for events
on a player
通过lessons
。但你对它们的命名可能会有所不同。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)