2012-01-07 72 views
1

我正在創建一個由學校,課程,學生和教師組成的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 

我如何設置我的模型和協會,使這項工作?

謝謝。

回答

0

我可能錯過了一些東西,但如果你用「用戶」添加class_name到你們的關係它應該工作:

class School < ActiveRecord::Base 
    has_many :courses 
    has_many :students :through enrollments, :class_name => "User" 
    has_many :teachers :through courses, :class_name => "User" 
end 

class Course < ActiveRecord::Base 
    has_one :teacher, :class_name => "User" 
    belongs_to :school 
    has_many :students :through enrollments, , :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_many :courses 
    has_many :schools 
end 
+0

謝謝,這是非常有幫助的。 – Deonomo 2012-01-07 17:59:18

+0

'class_name'實際上在':through'關聯中被忽略。與'primary_key'和'foreign_key'一起 – Azolo 2012-01-07 19:57:56

3

使用繼承。

教師和學生從用戶模型繼承。您可以諮詢http://api.rubyonrails.org/classes/ActiveRecord/Base.html瞭解更多信息。請務必在您的用戶表中創建一個「類型」列或同等字體。

class User < ActiveRecord::Base 
end 

class Student < User 
end 

class Teacher < User 
end 

Rails會單獨對待他們,但他們仍然會在用戶存在table.Let我知道如果你需要進一步的幫助

+0

嗯,我不確定我想在我的用戶表中創建一個類型列,因爲同一個用戶有時可能是學生,有時候會成爲老師。例如,你可以在一門課程中學習一門課程。 – Deonomo 2012-01-07 18:00:45

+0

我認爲sohaib就在這裏。您可以創建一個類型列,而不必擔心它。根據類型,從Active Record收到的對象將是學生或教師。它只是另一層抽象。 – 2012-01-07 18:38:16

+0

這是否允許同一個用戶既是學生又是老師? – Deonomo 2012-01-07 18:47:42

0

添加teachers_idcourses和使用belongs_to代替has_one。然後添加一個class_name選項。

class School < ActiveRecord::Base 
    has_many :courses 
    has_many :students :through enrollments 
    has_many :teachers :through courses 
end 

class Course < ActiveRecord::Base 
    belongs_to :teacher, :class_name => 'User' 
    belongs_to :school 
    has_many :students :through enrollments 
end 

class User < ActiveRecord::Base 
    has_many :courses 
    has_many :schools, :through enrollments 
    has_many :teachers, :through :courses 
end