Using the union model to bind the model to itself

I have two models:

  • User
  • MentoringRelationship

MentoringRelationship is a join model that has a mentor_id column and a mentee_id column (both of these are user_ids from the users table).

How can I specify a relationship called "trustees" in the User class that will return all users mentored by that user using the MentoringRelationships join table? What relationships do we need to declare in the User model and in the MentoringRelationship model?

+2


a source to share


4 answers


Thanks to http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through I was able to work something together.

in 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

      



in the app / models / mentoring_relationship.rb

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

      

0


a source


At the top of my head, referring to the 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

      



Unconfirmed, but looks like it should work.

+2


a source


You can do this using the following methods. In 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

      

0


a source


I believe it works ...

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

      

With this code, you can use

@user = User.find(:first)
@user.mentees
@user.mentors

      

0


a source







All Articles