2017-06-22 71 views
0

我有两个模型:Player和Event,它们之间有两个连接表,参与者和课程。Rails:相同两个模型之间的多个Join表

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,生成的查询将使用课程连接表而不是参与者。

有没有更好的方法来做到这一点?

编辑:下面是连接表款:

class Lesson 
    belongs_to :player 
    belongs_to :event 
end 

class Participant 
    belongs_to :player 
    belongs_to :event 
end 
+0

好像你想教训belong_to事件。 –

+0

谢谢。我刚刚更新了原始文件,以显示包含belongs_to事件的连接表(课程和参与者)的模型。你还有其他建议吗? – aprilone

回答

0

可以使用CLASS_NAME选项更改has_many关联的一个名称,但仍然与其他类关联。在我的示例中,我使用students代替players,代码为eventlessonslectures代码events,代码为playerlessons。但是你的名字可能会有所不同。

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 
+0

嗨迈克尔。谢谢你的帮助。我不确定我明白。如果我将'class_name:“Player”'和'class_name:“Event”'添加到模型中,那么'@ player.events'仍然使用课程连接表**而不是参与者... – aprilone

+0

你还有无论是作为'has_many:events,...'还是你在其中之一上改变了名字......如果你没有将':events'改成其中的一个,发生的事情是第二个has_many,是压倒第一。 –

+0

现在明白了,谢谢你的帮助! – aprilone

相关问题