Mongoid 文档to_json包括所有嵌入的文档,每个文档上都没有":include"



给定一个任意的monid文档,我如何将其转换为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"}]}]}

这样的语句存在吗?如果不是,那么我唯一的选择是回避文档的结构并自己生成适当的include吗?如果有另一种方法可以将整个文档可视化,那会更好吗?

这个问题是由论坛上的垃圾回答的,但是他没有发布答案,所以我正在这样做。

答案是使用"doc.as_document。As_json ",它会给你整个文档。

pp doc.as_document.as_json

您可以在文档中覆盖#to_json方法来添加所有include。

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

最新更新