我有一个模型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之间是正确的,那我有点迷失。
在这里,您应该使用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关系将团队和比赛相互关联。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句