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 ')}"
中,然後你知道一些真實可怕的事實
在rails中,這些被稱爲連接表,生病鏈接到文檔和答案很快解釋他們 –
謝謝,我很新的軌道,所以謝謝你花時間回答@TMP – matthew