Chris
Chris

Reputation: 729

Rails self-referential has_many through

I'm trying to make a self-referential user class with three basic user types - parent, student, and tutor. A student belongs to a parent and can also belong to a tutor. Of course, the way I have it written, rails only recognizes the parent having students. User.students always returns empty if the user is a tutor, but it works when the user is a parent. Any ideas?

class User < ActiveRecord::Base
# Sets up the tutor has_many students assocation
has_many :tutees, :foreign_key=>"tutor_id",
                :class_name=>"Relationship"
has_many :students, :through=>:tutees

# Sets up the student has_many tutors association
has_many :mentors, :foreign_key=>"student_id",
                 :class_name=>"Relationship"
has_many :tutors, :through=>:mentors

# Sets up the parent has_many students assocation
has_many :children, :foreign_key=>"parent_id",
                  :class_name=>"Relationship"
has_many :students, :through=>:children

# Sets up the student has_many parents 
has_many :mommies, :foreign_key=>"student_id",
                 :class_name=>"Relationship"
has_many :parents, :through=>:mommies

The Relationship class:

class Relationship < ActiveRecord::Base
 belongs_to :tutor, :class_name=>"User"
 belongs_to :student, :class_name=>"User"
 belongs_to :parent, :class_name=>"User"
end

The sections (parent, student, tutor) are each their own class as well. Basic user info is in the User class while data particular to tutors is in the Tutor class.

Upvotes: 2

Views: 1244

Answers (1)

Ashish
Ashish

Reputation: 5791

It is happening because of the same name (students) of relationships.

In your case,
has_many :students, :through=>:tutees
overrides by
has_many :students, :through=>:children
relation.

So you need to use different name then it will work.

-Ashish

Upvotes: 1

Related Questions