gpt4 book ai didi

ruby - DataMapper 中的关联

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:13 29 4
gpt4 key购买 nike

我在以下代码中遇到关联问题。

我遇到的错误是对最后一行代码的评论。

编辑:我简化了代码...

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)

最佳答案

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")

关于ruby - DataMapper 中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288758/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com