1
class CreateMatches < ActiveRecord::Migration
  def self.up
    create_table :matches do |t|
      t.integer :result_home
      t.integer :result_away
      t.references :clan, :as => :clan_home
      t.references :clan, :as => :clan_away

      t.references :league

      t.timestamps
    end
  end

  def self.down
    drop_table :matches
  end
end

I think code clears everything, I need to reference result_home to one clan and result_away to another. What is the best way to do so? I could create has_and_belongs_to_many but i think it's not good way in this case.

methyl
  • 3,272
  • 2
  • 25
  • 34

1 Answers1

1

This looks like a join association call it Match, and

class Clan < ActiveRecord::Base
  has_many :home_matches, :class_name => 'Match', :foreign_key => :clan_home
  has_many :away_matches, :class_name => 'Match', :foreign_key => :clan_away
  has_many :opponents_at_home, :through => :home_matches, :source => :clan
  has_many :opponents_away, :through => :away_matches, :source => :clan
end

class Match < ActiveRecord::Base
  belongs_to :clan_home, :class_name => 'Clan'
  belongs_to :clan_away, :class_name => 'Clan'
end

This is a little beyond my personal experience and I'm not 100% clear on the interpretation of the documentation for :source (check http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html). However, I think this will be along the right lines. YMMV.

Comments and improvements are welcome!

Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
  • What if I'd like to add what players played in home team and away team? – methyl Feb 26 '11 at 12:38
  • There's a number of things you could do. You could encapsulate the members in a `Team` model and have `belongs_to :away_team...` etc on `Match`, or you could add a `has_many :away_team_members...` etc straight on the `Match`. – Mike Tunnicliffe Feb 26 '11 at 13:00