mongoid文档to_json包括所有嵌入文档,每个文档没有':include'

时间:2011-12-08 15:36:59

标签: ruby json mongoid

给定一个任意mongoid文档如何将其转换为JSON并包含任何嵌入式结构,而不在我的to_json语句中明确包含这些结构。

例如:

#!/usr/bin/env ruby
require 'mongoid'
require 'json'
require 'pp'

class Doc
  include Mongoid::Document
  include Mongoid::Timestamps

  field :doc_specific_info    , type: String 

  embeds_many :persons
end

class Person
  include Mongoid::Document

  field :role                  , type: String
  field :full_name             , type: String

  embeds_many :addresses
  embedded_in :Doc
end

class Address
  include Mongoid::Document

  field :full_address       , type: String

end

doc = Doc.new
doc.doc_specific_info = "TestReport"

p = Person.new
p.role = 'buyer'
p.full_name = 'JOHN DOE'
doc.persons << p

a = Address.new
a.full_address =  '1234 nowhere ville' 
doc.persons.first.addresses << a

# THIS STATEMENT
pp JSON.parse(doc.to_json(:include => { :persons => { :include => :addresses } }  ) )
#   GIVES ME
#   {"_id"=>"4ee0d30fab1b5c5743000001",
#    "created_at"=>nil,
#    "doc_specific_info"=>"TestReport",
#    "updated_at"=>nil,
#    "persons"=>
#     [{"_id"=>"4ee0d30fab1b5c5743000002",
#       "full_name"=>"JOHN DOE",
#       "role"=>"buyer",
#       "addresses"=>
#        [{"_id"=>"4ee0d30fab1b5c5743000003",
#          "full_address"=>"1234 nowhere ville"}]}]}

# THIS STATEMENT
pp JSON.parse(doc.to_json() )
#  GIVES ME
#  {"_id"=>"4ee0d2f8ab1b5c573f000001",
#   "created_at"=>nil,
#    "doc_specific_info"=>"TestReport",
#     "updated_at"=>nil}

所以我想要的是这样的声明:

   # FOR A STATEMENT LIKE THIS
    pp JSON.parse(doc.to_json( :everything }  ) )
    #   TO GIVE ME THE COMPLETE DOCUMENT LIKE SO:
    #   {"_id"=>"4ee0d30fab1b5c5743000001",
    #    "created_at"=>nil,
    #    "doc_specific_info"=>"TestReport",
    #    "updated_at"=>nil,
    #    "persons"=>
    #     [{"_id"=>"4ee0d30fab1b5c5743000002",
    #       "full_name"=>"JOHN DOE",
    #       "role"=>"buyer",
    #       "addresses"=>
    #        [{"_id"=>"4ee0d30fab1b5c5743000003",
    #          "full_address"=>"1234 nowhere ville"}]}]}

这样的陈述是否存在?如果没有,那么我唯一的选择是重复使用文档的结构并生成适当的包含自己?如果还有另一种方法来可视化整个文档会更好吗?

2 个答案:

答案 0 :(得分:14)

论坛上的rubish回答了这个问题,但他没有发表回答,所以我这样做了。

答案是使用“doc.as_document.as_json”,它将为您提供整个文档。

pp doc.as_document.as_json

答案 1 :(得分:1)

您可以覆盖文档中的#to_json方法以添加所有包含。

class Person

  def to_json(*args)
    super(args.merge({:include => { :persons => { :include => :addresses } } } )
  end
end

现在你可以做到这一切

person.to_json()

如果您想要仅使用:everything选项返回完整版,您可以执行以下操作:

class Person

  def to_json(*args)
    if args[0] == :everything
      super(args.merge({:include => { :persons => { :include => :addresses } } } )
    else
      super(args)
    end
  end

end