我正在使用DataMapper 1.2.0并尝试定义要保存在数据库中的自定义属性类型。我试图理解我应该如何做到这一点,但我不断得到NoMethodError
。
对象是Dog
,但是这种类型来自我无法控制的gem,所以我不能让它继承自DataMapper::Property::Object
,所以我想我需要创建一个新类型这将是自定义属性(DatabaseDog
)。我对the documentation的理解是它需要两种方法:
#load(value)
从数据库中获取一个字符串并返回它代表的Dog
#dump(value)
获取Dog
并返回将保留在数据库中的字符串我不断收到错误的事实让我觉得我误解了这一点。
我应该如何正确创建此自定义类型?
编辑:我稍微更改了dump方法,发现它一直收到字符串。为什么#dump
接收字符串作为参数?它不应该收到我正在分配的Dog
对象吗?
# The setup
require 'dm-core'
require 'dm-migrations'
require 'dm-sqlite-adapter'
class Dog
attr_accessor :name
end
class DatabaseDog < DataMapper::Property::Text
def load(value)
d = Dog.new
d.name = value
d
end
def dump(value)
puts "got here: #{value.inspect}"
if value.nil?
value
else
value.name
end
end
end
class User
include DataMapper::Resource
property :id, Serial, key: true
property :pet, DatabaseDog
end
DataMapper.setup(:default, "sqlite3://#{File.join(Dir.pwd, "users.db")}")
DataMapper.finalize
DataMapper.auto_upgrade!
# Finally, the test
ein = Dog.new
ein.name = "Ein"
spike = User.create
spike.pet = ein
spike.save #=> NoMethodError
got here: nil
got here: "#<Dog:0x007fca399b7d40>"
./test.rb:19:in `dump': undefined method `name' for "#<Dog:0x007fba19960c00>":String (NoMethodError)
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/property.rb:700:in `valid?'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource/persistence_state/dirty.rb:88:in `block in valid_attributes?'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource/persistence_state/dirty.rb:87:in `each_key'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource/persistence_state/dirty.rb:87:in `valid_attributes?'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource/persistence_state/dirty.rb:21:in `commit'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:956:in `_persist'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:987:in `block in update_with_hooks'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:984:in `catch'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:984:in `update_with_hooks'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:1021:in `save_self'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:1006:in `block in _save'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:1222:in `run_once'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:1005:in `_save'
from (...)/test/.bundle/gems/dm-core-1.2.0/lib/dm-core/resource.rb:405:in `save'
from ./test.rb:42:in `<main>'
答案 0 :(得分:0)
根据文档,DatabaseDog应该继承自DataMapper :: Property :: Object而不是DataMapper :: Property :: Text。