0

我正在使用 DataMapper 1.2.0 并尝试定义自定义属性类型以保存在数据库中。我试图了解我应该如何做到这一点,但我不断得到一个NoMethodError.

对象是 a Dog,但这种类型来自我无法控制的 gem,所以我不能让它继承自DataMapper::Property::Object,所以我认为我需要创建一个新类型,它将作为自定义属性(DatabaseDog)。我从文档中的理解是它需要两种方法:

  • #load(value)从数据库中获取一个字符串并返回Dog它所代表的
  • #dump(value)接受一个Dog并返回一个字符串,该字符串将保存在数据库中

我不断收到错误的事实让我认为我误解了这一点。

我应该如何正确创建此自定义类型?

编辑:我稍微改变了转储方法,发现它一直在接收一个字符串。为什么#dump接收字符串作为参数?它不应该接收Dog我分配的对象吗?

测试.rb

# 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>'
4

1 回答 1

0

根据文档,DatabaseDog 应该继承自 DataMapper::Property::Object 而不是 DataMapper::Property::Text。

于 2013-04-17T13:45:28.480 回答