class Api::StoresController < ApplicationController respond_to :json def index @stores = Store.all(:include => :products) respond_with @stores end end
Returns only stores without their products, as well as
Store.find(:all).to_json(:include => :products)
The association is being tested, I see nested products in the console, for example,
Store.first.products
What is the right way to get their products included in MongoMapper?
Here are my models:
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
When I tried Scott's suggestion, I added the following to the Store model:
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
And in the controller:
def index @stores = Store.all_including_nested respond_with @stores end
Which looks like it should work? Assuming the hash array will be called #to_json, and then the same thing will happen with every hash and each Product + Service. I read through the ActiveSupport :: JSON source, and so far this is what I suffered from it.
But, while not working ... :(
json ruby-on-rails mongomapper responders
oliverbarnes
source share