使用连接模型将模型与自身相关联

时间:2010-05-19 04:43:22

标签: ruby-on-rails activerecord

我有两种模式:

  • 用户
  • MentoringRelationship

MentoringRelationship是一个连接模型,它有一个mentor_id列和一个mentee_id列(这两个引用来自users表中的user_id)。

如何使用MentoringRelationships连接表在User类上指定一个名为'mentees'的关系,该关系将返回此用户指导的所有用户?我们需要在User模型和MentoringRelationship模型中声明什么关系?

4 个答案:

答案 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

中的

  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
app / models / mentoring_relationship.rb

中的

  belongs_to :mentee, :class_name => "User"
  belongs_to :mentor, :class_name => "User"