Active Record error with Association

L

lrlebron

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top