Fred Fickleberry III
Fred Fickleberry III

Reputation: 2519

Two associations from the same model possible?

I have a model Country (which is the same as 'Team') and a model Match and I am trying to build a scenario where I have a Match record with both home & away teams.

The models

class Country < ActiveRecord::Base
  has_many :home_matches, :foreign_key => 'home', :class_name => "Match"
  has_many :away_matches, :foreign_key => 'away', :class_name => "Match"
end

class Match < ActiveRecord::Base
  belongs_to :home, :class_name => "Country", :foreign_key => "home"
  belongs_to :away, :class_name => "Country", :foreign_key => "away"
end

The schemas

  create_table "countries", :force => true do |t|
    t.string   "name"
    t.text     "bio"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "matches", :force => true do |t|
    t.datetime "matchdate"
    t.integer  "home"
    t.integer  "away"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Problem

This works well if I just want:

> canada.away_matches
> japan.home_matches

But how do I get all matches that a country is playing?

Update:

I found the answer in another reply. ActiveRecord has two association

I have updated my Country model with the following code:

def matches
  Match.where("home = ? OR away = ?", self, self)
end

Now I can query:

> canada.home_matches
> canada.away_matches
> canada.matches

And get the desired result.

Upvotes: 0

Views: 110

Answers (1)

Jatin Ganhotra
Jatin Ganhotra

Reputation: 7015

You are setting up the associations in a wrong way.
Go through this

  1. Single_Table_Inheritance wiki, and
  2. single-table-inheritance-and-where-to-use-it-in-rails

Upvotes: 1

Related Questions