2012-01-07 8 views
1

私は、学校、コース、学生、教師からなるWebアプリケーションを作成しています。Railsの関連付け - さまざまな種類のユーザーに関連付けを設定するにはどうすればよいですか?

学校には多くのコースがあり、コースには1人の教師と多くの学生がいます。

私は、1人のユーザーが1つのコースの先生になることができますが、別のコース(または別の学校のコースに参加している学生または教員)の生徒になる可能性があります。私はすべてのユーザーを1か所で追跡したいので、教師用のモデルと学生向けのモデルを作成したくありません。どのユーザーがコースに参加しているのかを示す登録テーブルがあります。

私は次のような何かをしたいと思います:

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

+0

'class_name'は実際に':through'関連で無視されます。 'primary_key'と' foreign_key'と一緒に – Azolo

3

使用の継承。

教師と生徒は、ユーザーモデルから継承されます。詳細については、http://api.rubyonrails.org/classes/ActiveRecord/Base.htmlまでご連絡ください。 Userテーブルには、必ず「タイプ」の列または同等のものを作成してください。

class User < ActiveRecord::Base 
end 

class Student < User 
end 

class Teacher < User 
end 

Railsはそれらを個別に処理しますが、彼らはまだあなたが

+0

ええと、同じユーザーが学生で、時には先生かもしれないので、私は自分のユーザーテーブルに型の列を作成したいとは思っていません。たとえば、1つのコースを異なるコースの学生として教えることができます。 – Deonomo

+0

私はsohaibがここにいると思います。型の列を作成することはできますが、それについてはまったく気にする必要はありません。 Active Recordから受け取ったオブジェクトは、タイプに応じてStudentまたはTeacherのいずれかになります。その抽象化のただ一つの層。 –

+0

これは、同じユーザーが学生と教師の両方になることを許可しますか? – Deonomo

0

coursesteachers_id列を追加し、代わりにhas_onebelongs_toを使用し、さらに支援が必要な場合は、私が知っているtable.Letユーザーに存在しています。次に、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 
関連する問題