鉴于此mongoid“报告”文档对象embeds_one位置对象:
{
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
代码的外观是什么,除了“geocode”,它是位置的一部分?
答案 0 :(得分:0)
适合我:
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”:“4dab2655b4e4cf2fa6000001”,“comment”:“comment”,“location”:{“_ id”:“4dab2655b4e4cf2fa6000002”,“address”:“elm street”}}
如果您希望Location始终省略地理编码,那么您应该在Location类中重新定义serializable_hash:
def serializable_hash(options = nil)
options ||= {}
options[:except] = :geocode
super(options).tap do |attrs|
serialize_relations(attrs, options) if options[:include]
end
end