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

コードはすべてをクリアすると思います。result_home を 1 つのクランに参照し、result_away を別のクランに参照する必要があります。そうするための最良の方法は何ですか?has_and_belongs_to_many を作成できましたが、この場合は良い方法ではないと思います。

4

1 に答える 1

1

Matchこれは、それを呼び出す結合結合のように見えます。

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

これは私の個人的な経験を少し超えており、( http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html:sourceを確認してください)のドキュメントの解釈について 100% 明確ではありません。しかし、これは正しい方向に沿っていると思います。YMMV

コメントと改善は大歓迎です!

于 2011-02-26T12:30:52.467 に答える