2010-03-13 74 views
1

我是新來的鐵軌,並自願幫助當地的高中軌道團隊與一個簡單的數據庫,追蹤跑步者的表現。目前,我有三種模型:跑步者,Race_Data和Races。我有以下關聯。ActiveRecord協會問題

Runners have_many Race_Data 
Races have_many Race_Data 

我也想建立關聯運動員Have_Many賽通過Race_Data,但我看我畫的圖,已經有一個多從Race_data到一個種族關係。具有多Race_Data和Race_Data的跑步者組合是否意味着Runners和Races之間的Many_to_Many關係?

回答

1

您描述的關係是隱含的,但使用它會涉及比可能需要更復雜的代碼。我想你想要的東西更像

class Runner < ActiveRecord::Base 
    has_many :entries 
    has_many :races, :through => :entries 
end 
class Race < ActiveRecord::Base 
    has_many :entries 
    has_many :runners, :through => :entries 
end 
class Entry < ActiveRecord::Base 
# I suggest this is a more expressive name than "Race_Data" 
    belongs_to :runner 
    belongs_to :race 
end 

這應該是足夠做的東西是這樣的:

bob = Runner.new(:name=>'Bob') 
joe = Runner.new(:name=>'Joe') 
race = Race.new(:race_date=>'20100313') 
race.entries.create(:runner=>joe, :position=>1) 
race.entries.create(:runner=>bob, :position=>2) 
bob.races.all #=> [#<Race id: 1, race_date: "2010-03-13"] 
bob.entries.all #=> => [#<Entry id: 2, runner_id: 1, race_id: 1, position: 2] 
+0

麥克, 感謝您很大的反響。關於使用條目而不是race_data的建議也很好。 吉姆 – Mutuelinvestor