Self-referential has_many :through associations


I got running very well, but I am stuck now… need some lights…

got a User class

has_many :credentials_as_referee, :foreign_key => ‘referee_id’,
:class_name => ‘Credential’
has_many :credentials_as_referenced_user, :foreign_key =>
‘referenced_user_id’, :class_name => ‘Credential’
has_many :referees, :through => :credentials_as_referenced_user
has_many :referenced_users, :through => :credentials_as_referee

I can easily get all referees or all referenced_users for a specific
user, but more tricky
aUser.referees or aUser.refrenced_users

I can get all credentials , even more I can get all
validated_credentials (based on a flag 0-1 in Credential)

but I would like to get all valid referees or referenced_users, based on
the flag in the Credential join model… don’t know how to write it

thanks fyl


I haven’t tested the below, but I was working on something very similar
this weekend so, I believe it should work… assuming I understood your
questions correctly.

has_many :validated_credentials_as_referee, :foreign_key =>
‘referee_id’, :class_name => ‘Credentials’, :conditions => ‘flag = 1’
has_many :validated_referenced_users, :through =>


I wrestled with this previously. Not sure which version of rails you are
on, but I had to employ the fixes in bug #6466 (I’m on edge rails).

I also added the extensions stuff to get the << operator working.

has_many :connections,
:foreign_key => ‘source_user_id’,
:class_name => ‘Connection’

has_many :refereeships,
:class_name => ‘Connection’,
:foreign_key => “source_user_id”,
:conditions => “connection_type = ‘R’”
has_many :referees_out,
:through => :refereeships,
:source => :target_user do
def construct_join_attributes(associate)
super.merge({:connection_type => ‘R’})