2011-03-20 52 views
0

鑑於這種mongoid「報告」文檔對象embeds_one位置對象:JSON序列化,除了在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 

什麼代碼看起來象到除「地址解析」,這是地點的一部分?

+0

你嘗試做的一樣位置分類s,例如:除了=>:地理編碼? – Roman 2011-04-15 10:27:39

+0

是的........................ – BenB 2011-04-17 12:56:13

回答

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」, 「評論」: 「評論」, 「位置」:{ 「_ ID」: 「4dab2655b4e4cf2fa6000002」,「地址「:」猛鬼街「}}

,如果你想要的位置總是忽略地理編碼,那麼你應該重新定義位置類中的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