Rails模型关系has_many belongs_to

时间:2013-09-07 15:56:16

标签: ruby-on-rails activerecord relationship

我有一个模型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

我希望能够通过比赛创建一个新的团队。而且我不想要重复的匹配记录或团队记录。如果这个协会在Team和Match之间是正确的,我有点迷茫。

2 个答案:

答案 0 :(得分:0)

您应该使用 has_and_belongs_to_many 关系。

<强> Match.rb

class Match < ActiveRecord::Base
  has_and_belongs_to_many :teams
end

<强> Team.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关系将团队和匹配相互关联。

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