【问题标题】:Rails model references questionRails 模型参考问题
【发布时间】:2011-02-26 12:13:29
【问题描述】:
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 但我认为在这种情况下这不是好方法。

【问题讨论】:

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


    【解决方案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

    欢迎提出意见和改进!

    【讨论】:

    • 如果我想添加主队和客队的球员怎么办?
    • 您可以做很多事情。您可以将成员封装在Team 模型中,并在Match 上添加belongs_to :away_team... 等,或者您可以直接在Match 上添加has_many :away_team_members... 等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2017-12-19
    • 1970-01-01
    • 2015-02-03
    • 2014-10-03
    相关资源
    最近更新 更多