我有以下自定义字段类型,允许我保存GeoJSON LineString,同时将字段视为点数组:
class GeoLineString
attr_reader :coordinates
def initialize(array)
@coordinates = array
end
# Converts an object of this instance into a database friendly value.
def mongoize
{
"type" => "LineString",
"coordinates" => @coordinates
}
end
def as_json(options={})
mongoize
end
class << self
# Get the object as it was stored in the database, and instantiate
# this custom class from it.
def demongoize(object)
return self.new(object["coordinates"]) if object.is_a?(Hash)
end
# Takes any possible object and converts it to how it would be
# stored in the database.
def mongoize(object)
case object
when GeoLineString then object.mongoize
when Array then GeoLineString.new(object).mongoize
else object
end
end
# Converts the object that was supplied to a criteria and converts it
# into a database friendly form.
def evolve(object)
case object
when GeoLineString then object.mongoize
else object
end
end
end
end
我在我的模型中使用如下:
class Track
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :coordinates, type: ::GeoLineString
index({ coordinates: "2dsphere" }, { min: -200, max: 200 })
end
这可以按预期工作,但是当我想要更改GeoLineString字段内部的坐标时,mongoid不会将字段“coordinates”识别为脏,因此不会在数据库中更新它。例如:
t=Track.last
=> #<Track _id: 568a70e6859c862ee1000000, created_at: 2016-01-04 13:17:40 UTC, updated_at: 2016-01-04 13:17:40 UTC, name: nil, coordinates: {"type"=>"LineString", "coordinates"=>[[1, 2], [2, 2]]}>
t.coordinates.coordinates.push([3,3])
t
=> #<Track _id: 568a70e6859c862ee1000000, created_at: 2016-01-04 13:17:40 UTC, updated_at: 2016-01-04 13:17:40 UTC, name: nil, coordinates: {"type"=>"LineString", "coordinates"=>[[1, 2], [2, 2], [3, 3]]}>
t.changed?
=> false
我怎样才能让mongoid认识到价值已发生变化?