ActiveRecord协会问题

时间:2010-03-13 17:40:38

标签: ruby-on-rails activerecord associations

我是铁杆新手,并自愿帮助当地的High School Track团队提供一个跟踪跑步者表现的简单数据库。目前,我有三个模型:Runners,Race_Data和Races。我有以下协会。

Runners have_many Race_Data
Races have_many Race_Data

我还想通过Race_Data创建关联Runners Have_Many Races,但是当我看到我绘制的图表时,从Race_data到Races已经存在多对一的关系。具有许多Race_Data和Race_Data的Runners组合是否具有一个Race,这意味着Runners和Races之间存在Many_to_Many关系?

1 个答案:

答案 0 :(得分: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]