Forum: Ruby on Rails Self-referential has_many :through associations

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ee0293412faca21e4ebf3326ed9d5f8c?d=identicon&s=25 Kad Kerforn (kadoudal)
on 2007-01-15 17:04
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
3299251223f55753ec84719de39e6e53?d=identicon&s=25 Jon Garvin (Guest)
on 2007-01-15 17:30
(Received via mailing list)
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 =>
3a301d7ca78eb4da89bce878608add09?d=identicon&s=25 Ian Duggan (Guest)
on 2007-01-15 20:02
(Received via mailing list)
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'})
This topic is locked and can not be replied to.