您描述的關係是隱含的,但使用它會涉及比可能需要更復雜的代碼。我想你想要的東西更像
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]
麥克, 感謝您很大的反響。關於使用條目而不是race_data的建議也很好。 吉姆 – Mutuelinvestor