# Active Record error with Association

**URL:** <https://www.ruby-forum.com/t/active-record-error-with-association/102618>\
**Category:** Ruby\
**Created:** [December 8, 2006, 4:45am UTC](https://www.ruby-forum.com/t/active-record-error-with-association/102618 "2006-12-08T04:45:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 8, 2006, 4:45am UTC](https://www.ruby-forum.com/t/active-record-error-with-association/102618/1 "2006-12-08T04:45:46Z")

</div>

I am learning to use ActiveRecord so bear with me. I have a script that  
looks like this

class Product \< ActiveRecord::Base  
set\_primary\_key “ProductID”  
set\_table\_name “Product”  
has\_many :variants, :foreign\_key =\> ‘ProductID’  
end

class Variant \< ActiveRecord::Base  
set\_primary\_key “VariantID”  
set\_table\_name “ProductVariant”  
belongs\_to :product, :foreign\_key =\> ‘ProductID’  
has\_one :capacity, :foreign\_key =\> ‘CapacityID’  
has\_one :material, :foreign\_key =\> ‘MaterialID’  
end

class Capacity \< ActiveRecord::Base  
set\_primary\_key “CapacityID”  
has\_many :variants, :foreign\_key =\> ‘CapacityID’  
end

class Material \< ActiveRecord::Base  
set\_primary\_key “MaterialID”  
has\_many :variants, :foreign\_key =\> ‘MaterialID’  
end

widget = Product.find(“10”)  
puts widget.Name  
puts ‘-------------------------------------’

widget.variants.each do |v|  
puts v.Name.squeeze(" ").chop! + “\t\t In stock: \t” +  
v.Inventory.to\_s + “\tPrice: \t” + v.Price.to\_s + “\tCapacity: \t” +  
v.capacity.Name.to\_s  
puts “\t Material: \t” + v.material.Name.to\_s # this line breaks the  
script

end

The “puts “\t Material: \t” + v.material.Name.to\_s” line in the do  
loop triggers the following error:

## B2

654 - TB2 Cup & Bearin In stock: 0 Price: 80.0 Capacity: 300 KG  
ar4.rb:42: undefined method `Name' for nil:NilClass (NoMethodError) from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/associations/association_proxy.rb:110:in`each’  
from  
c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active\_record/associations/association\_proxy.rb:110:in  
`send' from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/associations/association_proxy.rb:110:in`method\_missing’  
from  
c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active\_record/associations/has\_many\_association.rb:90:in  
`method\_missing’  
from ar4.rb:40

The Materials table consists of two fields MaterialID, Name

Any ideas would be greatly appreciated.

thanks,

Luis
