【发布时间】:2011-03-02 09:54:10
【问题描述】:
我正在尝试创建一个具有三种基本用户类型的自引用用户类——家长、学生和导师。学生属于父母,也可以属于导师。当然,按照我写的方式,rails 只识别有学生的父母。如果用户是导师,则 User.students 总是返回空,但当用户是父母时它可以工作。有什么想法吗?
class User < ActiveRecord::Base
# Sets up the tutor has_many students assocation
has_many :tutees, :foreign_key=>"tutor_id",
:class_name=>"Relationship"
has_many :students, :through=>:tutees
# Sets up the student has_many tutors association
has_many :mentors, :foreign_key=>"student_id",
:class_name=>"Relationship"
has_many :tutors, :through=>:mentors
# Sets up the parent has_many students assocation
has_many :children, :foreign_key=>"parent_id",
:class_name=>"Relationship"
has_many :students, :through=>:children
# Sets up the student has_many parents
has_many :mommies, :foreign_key=>"student_id",
:class_name=>"Relationship"
has_many :parents, :through=>:mommies
关系类:
class Relationship < ActiveRecord::Base
belongs_to :tutor, :class_name=>"User"
belongs_to :student, :class_name=>"User"
belongs_to :parent, :class_name=>"User"
end
这些部分(家长、学生、导师)也是各自的班级。基本用户信息在 User 类中,而特定于导师的数据在 Tutor 类中。
【问题讨论】:
-
你的
Relationship班级是什么样的? -
我假设您问题中的每个部分也属于不同的类别,对吧?
-
贴出关系码。是的,每个部分(家长、学生、导师)也有自己的班级。
标签: ruby-on-rails ruby-on-rails-3 has-many-through has-many-polymorphs