Forum: Ruby on Rails Multiple joins to same mysql table (noob question)

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.
43ec876a9d1c5421b9f8293ace5aa071?d=identicon&s=25 Mitch Lasky (khamaj)
on 2005-12-06 01:43
I am working on a site that includes soccer match scheduling.  I have
the following basic mysql schema:

TABLE teams (

TABLE fixtures (

In the past, with mysql/php, I would have done something like this:

SELECT [...] FROM fixtures, teams AS t1, teams AS t2 WHERE AND;

I am stumped as to how to do this with RoR using the ActiveRecord
belongs_to and has_many associations.  I tried something like this to no

class Fixture < ActiveRecord::Base
  belongs_to :team,
             :foreign_key => "home_team_id"
  belongs_to :team,
             :foreign_key => "away_team_id"

with reciprocal references in the Team.rb model, but it didn't seem to

Any thoughts would be greatly appreciated.
58c44a4a506d878f9a112f1d7b7cb87e?d=identicon&s=25 jeremyevans0 (Guest)
on 2005-12-06 04:37
(Received via mailing list)
On 12/5/05, Mitch Lasky <> wrote:
> class Fixture < ActiveRecord::Base
>   belongs_to :team,
>              :foreign_key => "home_team_id"
>   belongs_to :team,
>              :foreign_key => "away_team_id"
>   end

You can't gave two different associations the same name.  You want:

class Fixture < ActiveRecord::Base
  belongs_to :home_team, :class_name=>'Team', :foreign_key =>
  belongs_to :away_team, :class_name=>'Team',  :foreign_key =>


Note that you won't be able to use eager loading for both teams on
such a table without modifying Rails via a patch or plugin.
This topic is locked and can not be replied to.