开发者

Using a join model to relate a model to itself

开发者 https://www.devze.com 2022-12-31 19:06 出处:网络
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 reference user_ids from the users table).

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 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 开发者_StackOverflowwe need to declare in the User model and in the MentoringRelationship model?


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.


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


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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消