3
我已经使用了MongoMapper几个星期了,并且像很多功能一样。其中最吸引人的之一是能够定义自定义键类型和验证方法(请参阅本页上的“自定义类型”:http://mongomapper.com/documentation/types.html)。MongoMapper自定义类型不工作
但是,我试着用它们进行一个小测试,验证方法并没有在我的情况下开火。下面的代码:
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
我省略了它从我的测试示例,因为结果是相同或不相同。
任何人都可以帮忙吗?非常感谢。
在我眼皮底下的全部时间。我从Mongoid转向了MongoMapper,并没有内化语法差异。非常感谢您的帮助@ chris-heald。 –