在下面的代码中,我遇到了关联问题。
我得到的错误是对最后一行代码的注释。
编辑:我简化了代码.
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)发布于 2011-09-02 22:01:26
create是一个类方法(类似于Java中的静态方法),因此不能对实例(在本例中为非实例)调用它:)
您可以像这样创建对象
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")发布于 2011-09-02 21:56:32
has 1创建一个访问器productoptionset,它最初是nil而不是集合。nil没有方法create。收藏品已经。
您可以通过以下方式创建和关联ProductOptionSet
Productoptionset.create(:name => 'Foo', :product => gps)https://stackoverflow.com/questions/7288758
复制相似问题