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])

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s