title: Including nested objects in JSON response, from MongoMapper objects
body: <pre><code>class Api::StoresController &lt; ApplicationController  
    respond_to :json
  
    def index
      @stores = Store.all(:include =&gt; :products)
      respond_with @stores
    end
  end
  </code></pre>
  
  <p>Returns only stores without their products, as does </p>
  
  <pre><code>Store.find(:all).to_json(:include =&gt; :products)
  </code></pre>
  
  <p>The association is tested, I can see the nested products in console ouput from, say,</p>
  
  <pre><code>Store.first.products
  </code></pre>
  
  <p>What's the correct way to get them products included with MongoMapper?</p>
  
  <p>Here are my models:</p>
  
  <pre><code>   class Store
       include MongoMapper::Document         
       many :products, :foreign_key =&gt; :store_ids 
     end
  
     class Product
       include MongoMapper::Document         
       key :store_ids, Array, :typecast =&gt; 'ObjectId'
       many :stores, :in =&gt; :store_ids
     end
  </code></pre>
  
  <p><em>UPDATE</em></p>
  
  <p>In trying Scott's suggestion, I've added the following to the Store model:</p>
  
  <pre><code>def self.all_including_nested
    stores = []
    Store.all.each do |store|
      stores &lt;&lt; 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
  </code></pre>
  
  <p>And in the controller:</p>
  
  <pre><code>def index
    @stores = Store.all_including_nested
    respond_with @stores
  end
  </code></pre>
  
  <p>Which <em>looks</em> like it should work? Assuming the array of hashes would have #to_json called on it, and then the same would happen to each hash and each Product + Service. I'm reading through ActiveSupport::JSON's source, and so far that's what I've grokked from it. </p>
  
  <p>But, not working yet... :(</p>