Rails 关联 - 如何为不同种类的用户设置关联? [英] Rails associations - how can I set up associations for different varieties of users?
问题描述
我正在创建一个由学校、课程、学生和教师组成的网络应用.
I'm creating a web app which consists of schools, courses, students, and teachers.
一所学校可以开设多门课程,而一门课程可以有一名老师和多名学生.
A school can have many courses and a course has one teacher and many students.
我遇到的问题是,单个用户可能是一门课程的老师,但可能是另一门课程的学生(甚至是不同学校课程的学生或老师).我不想为教师创建一个模型,为学生创建一个单独的模型,因为我想在一个地方跟踪我的所有用户.有一个注册表,其中列出了哪些用户被注册为课程的学生.
The problem I am running into is that a single user could be a teacher of one course, but a student in another course (or even a student or teacher in a course in a different school). I don't want to create a model for teachers and a separate model for students because I would like to track all my users in one place. There is an enrollment table which lists which users are enrolled as students in a course.
我想做如下事情:
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
但如果我只有一个用户表而不是两个单独的学生和教师表,这将不起作用.
But if I have only a users table and not two separate students and teachers tables, this won't work.
相反,我必须做类似的事情
Instead, I would have to do something like
class School < ActiveRecord::Base
has_many :users [that are teachers]
has_many :users :through enrollments [that are students]
end
如何设置我的模型和关联以使其正常工作?
How can I set up my model and associations to make this work?
谢谢.
推荐答案
使用继承.
教师和学生继承自用户模型.可以参考http://api.rubyonrails.org/classes/ActiveRecord/Base.html 了解更多信息.请务必在您的用户表中创建类型"列或等效列.
Teachers and students are inherited from the users model. You can consult http://api.rubyonrails.org/classes/ActiveRecord/Base.html for further information. Be sure to create a "type" column or equivalent in your User table.
class User < ActiveRecord::Base
end
class Student < User
end
class Teacher < User
end
Rails 会单独对待它们,但它们仍将存在于 User 表中.如果您需要进一步的帮助,请告诉我
Rails will treat them individually, but they will still exist in the User table.Let me know if you need further assistance
这篇关于Rails 关联 - 如何为不同种类的用户设置关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!