Create complex json response , with child relationship in rails


For mobile based app, sometimes you want to return json responses to the client.

Let say I have a class with Attraction which could be typically a name of city and the city could have multiples places of attractions.


class Attraction
 include MongoMapper::Document

key :city, String
many :places
end

A child class Place.rb


class Place
 include MongoMapper::Document

belongs_to :attraction
 key :type, String
key :description , String
 key :address, String
 key :website, String
 key :rating, Float
 belongs_to :attraction

end

 

Note it will not change for ActiveRecord class.

Now for call like /attractions.json i want all the attractions and also places mapped to attraction.


class AttractionsController < ApplicationController
 # GET /attractions
 # GET /attractions.json
 def index
 @attractions = Attraction.all
 render :json => @attractions.to_json(:include => [:places])

 end

end

:include  does the trick . Also if you want to include only selected fields from places class


render :json => @attractions.to_json(:include =>

[:places =>{ :only =>[:website,:address])