class Api::StoresController < ApplicationController
respond_to :json
def index
@stores = Store.all(:include => :products)
respond_with @stores
end
end
只退回没有产品的商店,同样如此
Store.find(:all).to_json(:include => :products)
关联经过测试,我可以在控制台输出中看到嵌套产品,例如,
Store.first.products
让他们的产品包含在 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
更新
在尝试 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
在控制器中:
def index
@stores = Store.all_including_nested
respond_with @stores
end
哪个看起来应该有效?假设哈希数组将调用#to_json,然后每个哈希和每个产品+服务都会发生同样的情况。我正在阅读 ActiveSupport::JSON 的源代码,到目前为止,这就是我从中得到的。
但是,还没有工作...... :(