Rails模型参考问题

时间:2011-02-26 12:13:30

标签: ruby-on-rails associations rails-models

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引用到一个clan并将result_away引用到另一个clan。 这样做的最佳方法是什么?我可以创建has_and_belongs_to_many,但我认为在这种情况下这不是好方法。

1 个答案:

答案 0 :(得分: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

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

欢迎评论和改进!