我有两种模式:
MentoringRelationship是一个连接模型,它有一个mentor_id列和一个mentee_id列(这两个引用来自users表中的user_id)。
如何使用MentoringRelationships连接表在User类上指定一个名为'mentees'的关系,该关系将返回此用户指导的所有用户?我们需要在User模型和MentoringRelationship模型中声明什么关系?
答案 0 :(得分:2)
在我的头顶,参考API docs:
class User < AR::B
has_many :mentees, :through => :mentoring_relationship
has_many :mentors, :through => :mentoring_relationship
end
class MentoringRelationship < AR::B
belongs_to :mentee, :class_name => "User"
belongs_to :mentor, :class_name => "User"
end
未经测试,但似乎这应该有效。
答案 1 :(得分:0)
您可以使用以下方式进行操作。 在user.rb中
def mentees
user = User.find_by_sql("select u.* from the users u, mentoring_relationships m where m.mentor_id = #{self.id} and u.id = m.mentee_id")
end
In controller
@user.mentees >> all of the users mentored by @user
答案 2 :(得分:0)
我相信这有效......
class User < ActiveRecord::Base
has_many :mentees, :foreign_key => :mentee_id,
:class_name => "MentoringRelationship"
has_many :mentors, :foreign_key => :mentor_id,
:class_name => "MentoringRelationship"
end
class MentoringRelationship < ActiveRecord::Base
belongs_to :mentee, :class_name => "User"
belongs_to :mentor, :class_name => "User"
end
使用此代码,您可以使用
@user = User.find(:first)
@user.mentees
@user.mentors
答案 3 :(得分:0)
感谢http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through,我能够把一些有用的东西放在一起。
app / models / user.rb 中的
app / models / mentoring_relationship.rb has_many :mentee_relationships, :class_name => 'MentoringRelationship', :foreign_key => :mentor_id
has_many :mentees, :through => :mentee_relationships, :source => :mentee, :foreign_key => :mentor_id
has_many :mentor_relationships, :class_name => 'MentoringRelationship', :foreign_key => :mentee_id
has_one :mentor, :through => :mentor_relationships, :source => :mentor, :foreign_key => :mentee_id
belongs_to :mentee, :class_name => "User"
belongs_to :mentor, :class_name => "User"