Ruby mongoid文档到_json,包括不带';的所有嵌入文档:包括';每一个
给定一个任意的mongoid文档,如何将其转换为JSON并包含任何嵌入式结构,而不在我的to_JSON语句中专门包含这些结构 例如:Ruby mongoid文档到_json,包括不带';的所有嵌入文档:包括';每一个,ruby,json,mongoid,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
#!/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}
有这样的说法吗?如果不是的话,那么我唯一的选择是重复文档的结构并生成适当的包含我自己的文档吗?如果有其他更好的方法来可视化整个文档?您可以覆盖文档中的#to_json方法来添加所有include
class Person
def to_json(*args)
super(args.merge({:include => { :persons => { :include => :addresses } } } )
end
end
现在你可以通过这样做来拥有一切
person.to_json()
如果要返回仅包含:所有内容的完整选项,可以执行以下操作:
class Person
def to_json(*args)
if args[0] == :everything
super(args.merge({:include => { :persons => { :include => :addresses } } } )
else
super(args)
end
end
end
这是由鲁比什在论坛上回答,但他没有发布答案,所以我这样做
答案是使用“doc.as\u document.as\u json”,它将为您提供整个文档
pp doc.as_document.as_json
你试过doc.as\u document.to\u json
@rubish-有没有办法包含特定的嵌入文档,而不是全部文档?@Nick我不知道有这样的事情,但是doc.as\u document
给了你一个散列,所以你可以使用散列来过滤密钥。只有
要求你了解mongoid对象。给定一组组成文档的任意对象,我想要全部内容。鲁比什回答了这个问题。doc.as_document.to_json就像一个符咒。
pp doc.as_document.as_json