我正在創建一個由學校,課程,學生和教師組成的Web應用程序。Rails關聯 - 如何爲不同類型的用戶設置關聯?
一所學校可以有很多課程,一門課程有一位老師和許多學生。
我遇到的問題是,單個用戶可能是一門課程的老師,而是另一門課程的學生(甚至是不同學校課程中的學生或教師)。我不想爲教師創建模型,也不想爲學生創建單獨的模型,因爲我想在一個地方跟蹤所有用戶。有一個註冊表列出了哪些用戶作爲學生註冊了課程。
我想這樣做如下:
class School < ActiveRecord::Base
has_many :courses
has_many :students :through enrollments
has_many :teachers :through courses
end
class Course < ActiveRecord::Base
has_one :teacher
belongs_to :school
has_many :students :through enrollments
end
class User < ActiveRecord::Base
has_many :courses
has_many :schools
end
但如果我只有一個用戶表,而不是兩個獨立的學生和教師的表,這是不行的。
相反,我會做一些像
class School < ActiveRecord::Base
has_many :users [that are teachers]
has_many :users :through enrollments [that are students]
end
我如何設置我的模型和協會,使這項工作?
謝謝。
謝謝,這是非常有幫助的。 – Deonomo 2012-01-07 17:59:18
'class_name'實際上在':through'關聯中被忽略。與'primary_key'和'foreign_key'一起 – Azolo 2012-01-07 19:57:56