2016-06-11 85 views
0
  1. 用戶可以教許多課題,每個課題可以有很多課程。
  2. 用戶可以加入由其他用戶創建的課程。

(1)很簡單,我實現了它如下:導軌 - 模型之間的多重關係

#user.rb 
has_many :topics 
has_many :lessons, through: :topic 

#topic.rb 
has_many :lessons 

#lesson.rb 
belongs_to :topic 
belongs_to :user 

(2)是許多一對多的關係,我認爲一個連接表 - 我們稱之爲匹配(額外點,以幫助我找到更好的名字!) - 是必需的。

如果我添加以下

#user.rb 
. 
. 
has_many :lessons, through: :match 

#lesson.rb 
. 
. 
has_many :users, through: :match 

#match.rb 
belongs_to :lesson 
belongs_to :user 

我想既然導軌無法獲得這兩種關係之間的差異,同時呼籲@ user.lessons,比如我會得到一個錯誤。

什麼是正確的方法?

p.s.我看到有很多類似於這個問題的問題,但我無法找到適當的解決方案來解決我的問題。

回答

0

我認爲你應該命名連接表user_lessons而不是匹配作爲連接表的Rails慣例。 重命名後,我想你應該寧願是這樣的:

user.rb

has_many :user_lessons 
    has_many :subscribed_lessons, through: :user_lessons, source: :lesson 

另外請注意,您的用戶

has_many :lessons, through: :topics #not :topic 

讓我知道是否可行。

+0

謝謝oreoluwa,你的答案很有意義。我會測試它,並會讓你知道,但我認爲這是正確的方法。感謝您提供關於命名的提示,我會按照您的建議。關於主題的'缺少'是一個錯字,但感謝您指出:)如果然後我需要像lesson.subscribed_users這樣的東西來看看用戶列表,我想我會添加'has_many:subscribed_users,通過:user_lessons,來源::用戶'對lesson.rb,對吧? – davideghz

+0

我想是的。請注意,你的源代碼應該是用戶而不是用戶 – oreoluwa