1

学校、コース、学生、教師で構成される Web アプリを作成しています。

学校には多くのコースがあり、コースには 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

しかし、users テーブルだけがあり、2 つの個別の学生と教師のテーブルがない場合、これは機能しません。

代わりに、次のようなことをしなければなりません

class School < ActiveRecord::Base
  has_many :users [that are teachers]
  has_many :users :through enrollments [that are students]
end

これを機能させるためにモデルと関連付けを設定するにはどうすればよいですか?

ありがとう。

4

3 に答える 3

3

継承を使用します。

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

class User < ActiveRecord::Base
end

class Student < User
end

class Teacher < User
end

Rails はそれらを個別に扱いますが、それらは引き続き User テーブルに存在します。さらにサポートが必要な場合はお知らせください

于 2012-01-07T17:45:25.460 に答える
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
于 2012-01-07T17:43:04.450 に答える
0

teachers_idに列を追加して、 の代わりにcourses使用します。次に、オプションを追加します。belongs_tohas_oneclass_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
于 2012-01-07T19:55:43.480 に答える