2014-03-12 124 views
0

我对轨道很陌生。我创建普通表没有问题,但我想弄清楚如何创建组合表。所以,例如会有一张运动桌和一张球队桌。然后,我想创建一个表,这是一个包含所有体育项目的运动队表,并且有一个值来自相应表的团队。我只是让比赛和团队桌子属于整个桌子还是有不同的方式。我将如何去做这件事。创建组合表

+0

在rails中,这些被称为连接表,生病链接到文档和答案很快解释他们 –

+0

谢谢,我很新的轨道,所以谢谢你花时间回答@TMP – matthew

回答

0

导轨指南协会是这些东西有很大的帮助:http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

这是一个特别有因为你要运动有,属于多支球队属于一对多的关系。

迁移应该是这样的:

class CreateSportsTeamsTable < ActiveRecord::Migration 
    def change 
    create_table :sports_teams, id: false do |t| 
     t.integer :sport_id 
     t.integer :team_id 
    end 
    add_index :sports_teams, [:sport_id, :team_id] 
    end 
end 

,这些模型应该是这样的:

class Sport < ActiveRecord::Base 
    has_and_belongs_to_many :teams 
end 

class Team < ActiveRecord::Base 
    has_and_belongs_to_many :sports 
end 

然后使用它们:

lax = Sport.create(name: "Lacrosse") 
lax.teams << Team.create(name: "Johns Hopkins University") 
lax.teams.first.name      #=> Johns Hopkins University 
jhu = Team.first 
jhu.sports.create(name: "Ultimate Frisbee") # Note there are many different ways to create the association 
puts "#{jhu.name} is the best at #{jhu.sports.collect{ |sport| sport.name }.join(' and ')}" 

中,然后你知道一些真实可怕的事实