1

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.

I would like to do something like the following:

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?

Thanks.

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_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
于 2012-01-07T19:55:43.480 回答