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
如何设置我的模型和关联以使其工作?
谢谢。
使用inheritance。
教师和学生inheritance自用户模型。 有关详细信息,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Base.html 。 务必在User表中创建“类型”列或等效项。
class User < ActiveRecord::Base end class Student < User end class Teacher < User end
Rails将单独处理它们,但它们仍将存在于User表中。如果您需要进一步的帮助,请告诉我
我可能错过了一些东西,但是如果你将class_name
添加到与“User”的关系中它应该有效:
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
在courses
添加teachers_id
列,并使用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