0

我有一个模型Match和一个模型Team,每个Match有两个teams,每个Team可以有多个Matches

Team: name:string

Match name:string team1:references team2:references

所以我的模型看起来像这样。

class Match < ActiveRecord::Base
  belongs_to :team1, :class_name => Team, :foreign_key => "team1_id"
  belongs_to :team2, :class_name => Team, :foreign_key => "team2_id"
end

class Team < ActiveRecord::Base
  has_many :matches
end

我希望能够通过比赛创建一个新团队。而且我不想要重复的比赛记录或团队记录。如果这种关联是团队和比赛之间的正确关联,我有点迷失了。

4

2 回答 2

0

在这里你应该使用has_and_belongs_to_many关系。

匹配.rb

class Match < ActiveRecord::Base
  has_and_belongs_to_many :teams
end

团队.rb

class Team < ActiveRecord::Base
  has_and_belongs_to_many :matches
end

并生成迁移以创建表以将团队和比赛相互关联:

rails g migration create_matches_teams_table

然后在生成的迁移文件中:

class CreateMatchTeams < ActiveRecord::Migration
  def self.up
    create_table :matches_teams, :id => false do |t|   # :id => false; is to  prevent the creation of primary key
        t.integer :match_id
        t.integer :team_id
    end
  end

  def self.down
    drop_table :matches_teams
  end
end

然后运行此迁移,您可以通过 habtm 关系将团队和比赛相互关联。

于 2013-09-07T16:03:00.473 回答
0

尝试这样的事情:

class Match < ActiveRecord::Base
  #home team
  belongs_to :team1, :class_name => Team, :foreign_key => "team1_id"
  #away team
  belongs_to :team2, :class_name => Team, :foreign_key => "team2_id"

  #this should only allow 1 match between each team
  validates :team1_id, :uniqueness => { :scope => :team2_id }
end

class Team < ActiveRecord::Base
  has_many :home_matches, :class_name => Match, :foreign_key => "team1_id"
  has_many :away_matches, :class_name => Match, :foreign_key => "team2_id"

  validates :name, :uniqueness => true

  def matches
    Match.where("team1_id = ? OR team2_id = ?", self.id, self.id)
  end
end
于 2013-09-07T16:13:48.860 回答