Chris Cummings
Chris Cummings

Reputation: 2067

Associations in DataMapper

I am having trouble with associations in the following code.

The error I'm getting is a comment on the last line of code.

Edit: I simplified the code...

require 'rubygems'
require 'data_mapper' # requires all the gems listed above
require 'pp'

DataMapper.setup(:default, 'sqlite:///Users/chris/Dropbox/HawkEye-DB Test/store.sqlite')

class Manufacturer
  include DataMapper::Resource
  property :id, Serial
  property :name, String

  has n, :products
end

class Product
  include DataMapper::Resource
  property :id, Serial    
  property :name, String

  belongs_to :manufacturer
  has 1, :productoptionset
end


class Productoptionset
  include DataMapper::Resource
  property :id, Serial    
  property :name, String

  belongs_to :product

end

DataMapper.auto_migrate!



# Make some manufactureres
gortex = Manufacturer.create(:name => 'Gortex')
garmin = Manufacturer.create(:name => 'Garmin')

gps = garmin.products.create(:name => 'GPS Unit')

samegps = Product.get(1)

pp samegps.productoptionset.create # undefined method `create' for nil:NilClass (NoMethodError)

Upvotes: 1

Views: 1329

Answers (2)

kreek
kreek

Reputation: 8834

create is a class method (kind of like a static method in Java) so it can't be called on instances (or non instances in this case) :)

You could create your objects like this

class Manufacturer
  include DataMapper::Resource
  property :id, Serial
  property :name, String

  has n, :products
end

class Product
  include DataMapper::Resource
  property :id, Serial    
  property :manufacturer_id, Integer
  property :name, String

  belongs_to :manufacturer
  has 1, :productoptionset
end


class Productoptionset
  include DataMapper::Resource
  property :id, Serial  
  property :product_id, Integer
  property :name, String

  belongs_to :product
end

DataMapper.auto_migrate!



# Make some manufactureres
gortex = Manufacturer.create(:name => 'Gortex')
garmin = Manufacturer.create(:name => 'Garmin')

garmin.products << Product.create(:name => 'GPS Unit')

samegps = Product.get(1)

samegps.productoptionset = Productoptionset.create(:name => "MyProductoptionset")

Upvotes: 4

undur_gongor
undur_gongor

Reputation: 15954

The has 1 creates an accessor productoptionsetwhich is initially nil rather than a collection. That nil has no method create. The collection has.

You can create and associate the ProductOptionSet via

Productoptionset.create(:name => 'Foo', :product => gps)

Upvotes: 3

Related Questions