Reputation: 8067
I have two models:
MentoringRelationship is a join model that has a mentor_id column and a mentee_id column (both of these reference user_ids from the users table).
How can I specify a relation called 'mentees' on the User class that will return all of the users mentored by this user, using the MentoringRelationships join table? What relations do we need to declare in the User model and in the MentoringRelationship model?
Upvotes: 2
Views: 170
Reputation: 8067
Thanks to http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through, I was able to put something together that works.
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 app/models/mentoring_relationship.rb
belongs_to :mentee, :class_name => "User"
belongs_to :mentor, :class_name => "User"
Upvotes: 0
Reputation: 8461
I believe this 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
Upvotes: 0
Reputation: 1013
Off 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
Untested, but it seems like this should work.
Upvotes: 2
Reputation: 47482
You can do it using following ways. 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
Upvotes: 0