Ruby on rails 除了在Mongoid中嵌入一个对象之外的JSON序列化?
给定嵌入一个位置对象的mongoid“Report”文档对象:Ruby on rails 除了在Mongoid中嵌入一个对象之外的JSON序列化?,ruby-on-rails,ruby,json,serialization,mongoid,Ruby On Rails,Ruby,Json,Serialization,Mongoid,给定嵌入一个位置对象的mongoid“Report”文档对象: { comment: "", location: { address: "391 Little Bourke St, Melbourne VIC 3000, Australia", geocode: { ll: "-37.813787,144.961227", } }, _id: "4d84af7f52f3d40539000021", } 如何删除位置哈希中的地理编码部分 例如,
{
comment: "",
location: {
address: "391 Little Bourke St, Melbourne VIC 3000, Australia",
geocode: {
ll: "-37.813787,144.961227",
}
},
_id: "4d84af7f52f3d40539000021",
}
如何删除位置哈希中的地理编码部分
例如,通过在报告模型中执行以下操作,可以很容易地删除注释字段:
def to_json(options={})
options[:except] ||= :comment
super(options)
end
除了作为位置的一部分的“地理代码”,代码看起来像什么?对我来说很有用:
require 'rubygems'
require 'mongoid'
Mongoid::Config.settings = {
"host" => "127.0.0.1",
"database" => "testing"
}
class Report
include Mongoid::Document
embeds_one :location
field :comment
end
class Location
include Mongoid::Document
field :address
field :geocode, :type => Hash
embedded_in :report
end
report = Report.new(:comment=>'comment', :location => {:address=>'elm street', :geocode => {:ll=>'-31'}})
puts report.to_json(:include=>:location, :except => :geocode)
收益率:
{“id”:“4DAB2655B4E4CF2FA600001”,“评论”:“评论”,“位置”:{“id”:“4DAB2655B4E4CF2FA600002”,“地址”:“榆树街”}
如果希望位置始终忽略地理代码,则应在Location类中重新定义可序列化的_散列:
def serializable_hash(options = nil)
options ||= {}
options[:except] = :geocode
super(options).tap do |attrs|
serialize_relations(attrs, options) if options[:include]
end
end
您是否尝试对Location类执行相同的操作,例如:except=>:geocode?