Self-referential symmetrical relation problem

I found the following code here:
http://www.railsweenie.com/forums/1/topics/1074

I 'm trying to add an additional "has_many :teamates" on the player
model but i cant figure out how to do it..

Any ideas?

Thanks in advance!
Chris

The Code:

# class Player < ActiveRecord::Base
# has_many :team_memberships
# has_many :teams, :through => :team_memberships
# end

class Player < ActiveRecord::Base
has_many :teammates, :class_name => ‘Player’
end

Then just add the field player_id to the players table, and it should work fine.

Ο/Η Luke Ivers έγραψε:

class Player < ActiveRecord::Base
  has_many :teammates, :class_name => 'Player'
end

Then just add the field player_id to the players table, and it should work
fine.

Nope, that wouldn't work. What i want is to find the teammates through
the other tables.

You'll likely need to go to SQL here... Join the tables together and
return the result based on the memberships of the instance-level
player.

  has_and_belongs_to_many :teammates,
    :join_table => TeamMembership.table_name,
    :finder_sql => "SELECT p2.* FROM #{TeamMembership.table_name} AS
t1 INNER JOIN #{Player.table_name} AS p1 ON t1.player_id = p1.id INNER
JOIN #{Player.table_name} AS p2 ON p2.team_id = t1.team_id WHERE p1.id
= \#{id} AND p2.id != \#{id}"

... i *think* that works...

Thanks a lot eden li! :slight_smile: