开发者

Rails model references question

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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜