两个团队之间的比赛铁路迁移

时间:2016-05-15 23:59:11

标签: ruby-on-rails migration relationship

我是一名刚开始使用ruby on rails的初学者,试图确定我的模型之间的关系MatchesTeams

我希望我的匹配两次引用Teams表,一次是homeTeam,另一次是awayTeam。我想我最大的问题是,我在模特中宣布关系不正确吗?

目前我甚至无法通过比赛拨打团队名称。

我希望能够调用Team.matches列出一个团队拥有的所有匹配项,无论是列为homeTeam还是offTeam,最终都可以为特定团队调用主场或客场比赛。

我也希望能够调用Match.teams / Match.homeTeam / Match.awayTeam来列出特定比赛的球队。

这是我到目前为止所拥有的:

匹配迁移

class CreateMatches < ActiveRecord::Migration
  def change
    create_table :matches do |t|
      t.references :homeTeam
      t.references :awayTeam
    end
  end
end

匹配模型

class Match < ActiveRecord::Base
    has_one :homeTeam, :class_name => 'Team'
    has_one :awayTeam, :class_name => 'Team'
end

团队模型

class Team < ActiveRecord::Base
    has_and_belongs_to_many :matches
end

提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

class Match < ActiveRecord::Base
    belongs_to :hometeam, :class_name => 'Team'
    belongs_to :awayteam, :class_name => 'Team'

 #if you want to select all teams of a match, you can create a method
 def teams
  Team.find(self.hometeam_id, self.awayteam_id)
 end
end

class Team < ActiveRecord::Base
  has_many :home, class_name: 'Match', foreign_key: 'hometeam_id'
  has_many :away, class_name: 'Match', foreign_key: 'awayteam_id'
end
相关问题