【问题标题】:MongoMapper Custom Types don't workMongoMapper 自定义类型不起作用
【发布时间】:2013-10-15 21:41:54
【问题描述】:

我已经使用 MongoMapper 几个星期了,并且喜欢它的许多功能。最吸引人的功能之一是能够定义自定义键类型和验证方法(请参阅本页上的“自定义类型”:http://mongomapper.com/documentation/types.html)。

但是,我尝试将它们与一个小测试一起使用,并且在我的情况下验证方法没有触发。代码如下:

require 'mongo_mapper'

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "mmtestdb"

class ACustomType
    def self.to_mongo(value)
        puts "to_mongo is being called"
        "A Safe Value"
    end
    def self.from_mongo(value)
        puts "from_mongo is being called"
        "A Safer Value"
    end
end

class TestClass
    include MongoMapper::Document

    key :my_name, type: ACustomType
end

TestClass.delete_all
new_object = TestClass.new
new_object.my_name = "Unsafe Value!"
puts new_object.inspect
new_object.save
puts TestClass.all.inspect

这是我的结果:

#<TestClass _id: BSON::ObjectId('525db435ab48651f64000001'), my_name: "Unsafe Value!">
[DEPRECATED] The 'safe' write concern option has been deprecated in favor of 'w'.
[#<TestClass _id: BSON::ObjectId('525db435ab48651f64000001'), my_name: "Unsafe Value!">]

我知道“写问题”问题,并使用https://github.com/mongomapper/mongomapper/issues/507 的解决方案对其进行了修补。这是代码:

# Monkey Patch to solve issue https://github.com/jnunemaker/mongomapper/issues/507
module MongoMapper
  module Plugins
    module Querying
      private
        def save_to_collection(options={})
          @_new = false
          collection.save(to_mongo, :w => options[:safe] ? 1 : 0)
        end
    end
  end
end

我在测试示例中省略了它,因为有或没有它的结果都是一样的。

有人可以帮忙吗?非常感谢。

【问题讨论】:

    标签: ruby mongodb mongomapper


    【解决方案1】:

    您只需将键定义为:

     key :my_name, ACustomType
    

    而不是:

     key :my_name, type: ACustomType
    

    key的方法签名是def key(name, type, options = {})

    【讨论】:

    • 一直就在我的眼皮底下。我从 Mongoid 来到 MongoMapper,并没有内化语法差异。非常感谢您的帮助@chris-heald。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 2012-09-10
    • 2017-02-01
    • 2016-11-24
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多