ruby - 如何构建带有子对象的 Mongoid 对象的 json 对象?

标签 ruby mongoid

我有两个简单的类

class Band
  include Mongoid::Document
  field :name, type:String
  has_many :members
end

class Member
  include Mongoid::Document
  field :name, type: String
  belongs_to :band
end

在我创建了两个用于测试目的的对象之后

Band.create(title: 'New Band')
Band.members.create(name: 'New Member')

我得到下一个数据库状态:

> db.bands.find()
{ "_id" : ObjectId("..."), "title" : "New Band" }
> db.members.find()
{ "_id" : ObjectId("..."), "name" : "New Member", "band_id" : ObjectId("...") }

当我尝试构建 Band 对象的 json 对象时,我得到了没有子对象的数据:

{"_id":"...","title":"New Band"}

但我需要这样的东西:

{"_id":"...","title":"New Band", "members" : {"_id":"...","title":"New Member"}}

如何用子构建json??

最佳答案

您可以覆盖serializable_hash:

class Member
  include Mongoid::Document
  field :name, type: String
  belongs_to :band

  def serializable_hash(options={})
    {
      id: id,
      name: name
    }
  end
end

class Band
  include Mongoid::Document
  field :title, type: String
  has_many :members

  def serializable_hash(options={})
    {
      id: id,
      title: title,
      members: members.inject([]) { |acc, m| acc << m.serializable_hash; acc }
    }
  end  
end

假设你有一个带成员的乐队:

band = Band.create(title: 'New Band')
band.members.create(name: 'New Member')

在这种情况下,band.to_json 将返回类似这样的内容:

"{\"id\":...,\"title\":\"New Band\",\"members\":[{\"id\":...,\"name\":\"New Member\"}]}"

关于ruby - 如何构建带有子对象的 Mongoid 对象的 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14285135/

相关文章:

ruby-on-rails - 构建查询时将 created_at 转换为时间戳

ruby - 关于 Ruby 中变量更改的问题

ruby-on-rails - Rails 和 Mongoid 的动态属性

ruby-on-rails - Rake 任务不断失败

rspec - 如何测试 Mongoid 将生成的查询类型?

ruby-on-rails - 使用 mongoid 和 rails 显示嵌套树的有效方法

ruby-on-rails - 从 React 调用 Shopify API

ruby-on-rails - 如何在 Ruby on Rails 3 中以非阻塞模式运行外部 shell 命令

ruby - fork : Resource temporarily unavailable when calling rvm from a shell script, 但 rvm 本身工作正常

Mongoid embeds_many : push document without save in order to preserve dirty state