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?
a source to share
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"
a source to share
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.
a source to share
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
a source to share