从MongoMapper对象中包含JSON响应中的嵌套对象

oli*_*nes 8 json ruby-on-rails mongomapper responders

class Api::StoresController < ApplicationController  
  respond_to :json

  def index
    @stores = Store.all(:include => :products)
    respond_with @stores
  end
end
Run Code Online (Sandbox Code Playgroud)

仅返回没有产品的商店

Store.find(:all).to_json(:include => :products)
Run Code Online (Sandbox Code Playgroud)

该关联已经过测试,我可以看到控制台中的嵌套产品,例如,

Store.first.products
Run Code Online (Sandbox Code Playgroud)

将他们的产品包含在MongoMapper中的正确方法是什么?

这是我的模特:

   class Store
     include MongoMapper::Document         
     many :products, :foreign_key => :store_ids 
   end

   class Product
     include MongoMapper::Document         
     key :store_ids, Array, :typecast => 'ObjectId'
     many :stores, :in => :store_ids
   end
Run Code Online (Sandbox Code Playgroud)

UPDATE

在尝试Scott的建议时,我在Store模型中添加了以下内容:

def self.all_including_nested
  stores = []
  Store.all.each do |store|
    stores << store.to_hash
  end
end

def to_hash
  keys = self.key_names
  hash = {}
  keys.each{|k| hash[k] = self[k]}
  hash[:products] = self.products
  hash[:services] = self.services
  hash
end
Run Code Online (Sandbox Code Playgroud)

在控制器中:

def index
  @stores = Store.all_including_nested
  respond_with @stores
end
Run Code Online (Sandbox Code Playgroud)

哪个看起来应该有效?假设哈希数组会在其上调用#to_json,那么每个哈希和每个产品+服务都会发生相同的情况.我正在阅读ActiveSupport :: JSON的源代码,到目前为止,这是我从中学到的东西.

但是,还没有工作...... :(

小智 17

看看这个as_json()方法.你把它放在你的模型中,定义你的json,然后简单地调用render :json方法并得到你想要的.

class Something
  def as_json(options={})
    {:account_name       => self.account_name,
     :expires_on         => self.expires_on.to_s,
     :collections        => self.collections,
     :type               => "Institution"}
  end
end
Run Code Online (Sandbox Code Playgroud)

你会发现self.collections哪个是很多关系.该模型还as_json()定义了:

class Collection
  def as_json(options={})
    {:name          => self.name,
     :title         => self.title,
     :isbn          => self.isbn,
     :publisher     => self.publisher,
     :monthly_views => self.monthly_views}
  end
end
Run Code Online (Sandbox Code Playgroud)

这个包含self.monthly_views代表另一种关系.

然后在你的控制器中:

@somethings = Something.all
render :json => @somethings
Run Code Online (Sandbox Code Playgroud)