Tuesday, April 5, 2011

ActiveRecord Associations Question

I'm new to rails and have volunteered to help out the local High School Track team with a simple database that tracks the runners performances. For the moment, I have three models: Runners, Race_Data and Races. I have the following associations.

Runners have_many Race_Data
Races have_many Race_Data

I also want create the association Runners Have_Many Races Through Race_Data, but as my look at the diagram I have drawn, there is already a many to one relationship from Race_data to Races. Does the combination of Runners having many Race_Data and Race_Data having one Race imply a Many_to_Many relationship between Runners and Races?

From stackoverflow
  • The relationship you describe is implied, but using it involves more complex code than might be needed. I think you want something more like

    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
    

    That should be enough to do stuff like this:

    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]
    
    Mutuelinvestor : Mike, Thanks for your great response. Also great suggestion on using Entries instead of race_data. Jim

0 comments:

Post a Comment