Rails 自引用 has_many 通过
我正在尝试创建一个具有三种基本用户类型(家长、学生和导师)的自引用用户类。学生既可以属于家长,也可以属于导师。当然,按照我的写法,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 类中。
I'm trying to make a self-referential user class with three basic user types - parent, student, and tutor. A student belongs to a parent and can also belong to a tutor. Of course, the way I have it written, rails only recognizes the parent having students. User.students always returns empty if the user is a tutor, but it works when the user is a parent. Any ideas?
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
The Relationship class:
class Relationship < ActiveRecord::Base
belongs_to :tutor, :class_name=>"User"
belongs_to :student, :class_name=>"User"
belongs_to :parent, :class_name=>"User"
end
The sections (parent, student, tutor) are each their own class as well. Basic user info is in the User class while data particular to tutors is in the Tutor class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
之所以发生这种情况,是因为同名(同学)的关系。
所以你需要使用不同的名称才能工作。
-阿什什
It is happening because of the same name (students) of relationships.
So you need to use different name then it will work.
-Ashish