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 TeamMembership < ActiveRecord::Base

belongs_to :player

belongs_to :team

end

class Team < ActiveRecord::Base

has_many :team_memberships

has_many :players, :through => :team_memberships

has_many :ratings

end

class Rating < ActiveRecord::Base

belongs_to :team

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 I. Ýãñáøå:

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.

On Mar 9, 6:26 pm, “eden li” [email protected] wrote:

… i think that works…

Thanks a lot eden li! :slight_smile:

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…

On Mar 9, 7:49 pm, “Trochalakis C.” [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs