您描述的关系是隐含的,但使用它会涉及比可能需要更复杂的代码。我想你想要的东西更像
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