2

我正在尝试创建一个具有三种基本用户类型的自引用用户类——家长、学生和导师。学生属于父母,也可以属于导师。当然,按照我写的方式,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 类中。

4

1 回答 1

1

发生这种情况是因为同名(学生)的关系。

在你的情况下,
has_many :students, :through=>:tutees
覆盖
has_many :students, :through=>:children
关系。

所以你需要使用不同的名字然后它才会起作用。

-阿什什

于 2011-03-02T10:15:26.660 回答