首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataMapper中的关联

DataMapper中的关联
EN

Stack Overflow用户
提问于 2011-09-02 20:11:45
回答 2查看 1.3K关注 0票数 1

在下面的代码中,我遇到了关联问题。

我得到的错误是对最后一行代码的注释。

编辑:我简化了代码.

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-02 22:01:26

create是一个类方法(类似于Java中的静态方法),因此不能对实例(在本例中为非实例)调用它:)

您可以像这样创建对象

代码语言:javascript
复制
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")
票数 4
EN

Stack Overflow用户

发布于 2011-09-02 21:56:32

has 1创建一个访问器productoptionset,它最初是nil而不是集合。nil没有方法create。收藏品已经。

您可以通过以下方式创建和关联ProductOptionSet

代码语言:javascript
复制
Productoptionset.create(:name => 'Foo', :product => gps)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7288758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档