简体   繁体   English

Rails模型关系has_many当属

[英]Rails Model relationship has_many belongs_to

I have a model Match and a model Team , each Match has two teams and each Team can have multiple Matches . 我有一个模型Match和一个模型Team ,每个Match都有两个teams ,每个Team可以有多个Matches

Team: name:string

Match name:string team1:references team2:references

So my models look like this. 所以我的模型看起来像这样。

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

I want to be able to create a new Team through a Match. 我希望能够通过比赛创建一个新的团队。 And I don't want either duplicate Match records nor Team records. 而且我既不想重复比赛记录也不想团队记录。 I am kinda lost, if this association is the right one between Team and Match. 如果这种关联在Team和Match之间是正确的,我有点迷失。

Here you should use has_and_belongs_to_many relationship. 在这里,您应该使用has_and_belongs_to_many关系。

Match.rb Match.rb

class Match < ActiveRecord::Base
  has_and_belongs_to_many :teams
end

Team.rb Team.rb

class Team < ActiveRecord::Base
  has_and_belongs_to_many :matches
end

And generate a migration to create table to associate teams and matches with each other: 并生成一个迁移以创建表以关联团队并相互进行比赛:

rails g migration create_matches_teams_table

Then in generated migration file: 然后在生成的迁移文件中:

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

Then run this migration, and you can associate teams and matches with each other via habtm relationship. 然后运行此迁移,您可以通过habtm关系将团队和比赛相互关联。

try something like this: 尝试这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM