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 引用到一个氏族,将 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

这有点超出我的个人经验,我对文档的解释并不是 100% 清楚:source(检查http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)。但是,我认为这将是正确的。YMMV

欢迎评论和改进!

于 2011-02-26T12:30:52.467 回答