class Api::StoresController < ApplicationController
respond_to :json
def index
@stores = Store.all(:include => :products)
respond_with @stores
end
end
只返回商店沒有自己的產品,一樣包括JSON響應嵌套的對象,從MongoMapper對象
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
UPDATE
在試圖斯科特的建議,我已經添加了以下到商店模式:
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
和Controller :
def index
@stores = Store.all_including_nested
respond_with @stores
end
其中看起來喜歡它應該工作嗎?假設哈希數組將被調用#to_json,那麼每個哈希和每個Product + Service都會發生同樣的情況。我正在閱讀ActiveSupport :: JSON的源代碼,到目前爲止,這正是我從中得到的結果。
但是,還沒有成型... :(
在時間的訣竅中,剛剛想出了相同的,並將與它更新的問題;)響應非常感謝,謝謝 – oliverbarnes 2011-02-25 19:52:19