Re: Issue with using has_many....

Jean Nibee
Thu, 06 Sep 2007 01:39:26 -0000

Daniel ----- wrote:
> On 9/5/07, Jean Nibee
<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:
>> > should be
>> => #<Gm:0xb721548c
@attributes={"last_modified"=>"0000-00-00 00:00:00",
>> "pool_id"=>"1",
"id"=>"1", "created"=>"0000-00-00
00:00:00",
>> "first_name"=>"Test",
"password"=>"1234",
"last_name"=>"User",
>> "user_name"=>"John",
"email_address"=>"jean-J0of1frlU80@public.gmane.org"}>
>> >> gm.players
>> NameError: uninitialized constant Gm::NhlStats
>>
>> --
>> Posted via http://www.ruby-forum.com/.
>>
>>
> hmmm  not sure on this one.  Try putting in a classname in there
>
>    has_many :players, :through => :teams, :source =>
> :nhl_stats, :class_name => "NhlStat",  :order =>
>  :player_name

Alrighty here''s what the problem was. It was actually in the definition
of the model I was using as the join.

I originally had:

class Team < ActiveRecord::Base
  belongs_to :gms
  belongs_to :nhl_stats
end

but should have had (I.E. singular symbols reference to my joined
model/tables):

class Team < ActiveRecord::Base
  belongs_to :gm
  belongs_to :nhl_stat
end

adding to this my ''final'' code to show a working
representation of the
Model as a Many to Many join reference...

class Gm < ActiveRecord::Base
  has_many :teams
  has_many :nhl_stats, :through => :teams
end

and

class NhlStat < ActiveRecord::Base
  has_many :teams
  has_many :gms, :through => :teams
end

Thusly we see a working relationship with some output...
>> gm = Gm.find(1)
=> #<Gm:0xb72b7fd4 @attributes={"pool_id"=>"1",
"id"=>"1",
"first_name"=>"Test",
"password"=>"1234",
"last_name"=>"User",
"user_name"=>"John",
"email_address"=>"jean-J0of1frlU80@public.gmane.org"}>
>> gm.players.each() { |p| puts "Player: #{p.player_name} \t G:
#{p.g}\t A: #{p.a} PM: #{p.pm}\n" };
?> false
Player: Marian Hossa             G: 43   A: 57 PM: 18
Player: Jarome Iginla            G: 39   A: 55 PM: 12
Player: Marc Savard              G: 22   A: 74 PM: -19
Player: Slava Kozlov             G: 28   A: 52 PM: 9
Player: Rod Brind''Amour          G: 26   A: 56 PM: 7
Player: Marc-Andre Fleury        G: 0    A: 3 PM: 0
Player: Justin Williams          G: 33   A: 34 PM: -11
Player: Brian Rolston            G: 31   A: 33 PM: 6
Player: Nathan Horton            G: 31   A: 31 PM: 15
Player: Ray Emery                G: 0    A: 1 PM: 0
Player: Manny Legace             G: 0    A: 0 PM: 0
Player: Michal Rozsival          G: 10   A: 30 PM: 10
Player: Joe Corvo                G: 8    A: 29 PM: 8
Player: Andrej Meszaros          G: 7    A: 28 PM: -15
Player: Mike Van Ryn             G: 4    A: 25 PM: -5

Yet again, this list has proved highly informative.