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

 

Problem while deleting few ruby gems.


It may happen that at time while deleting the ruby gem the error can be :

ERROR: While executing gem ... (Gem::InstallError)
Unknown gem rake >= 0

This generally happens when there are multiple gem paths.

type ‘gem env’

RubyGems Environment:
– RUBYGEMS VERSION: 1.6.2
– RUBY VERSION: 1.9.2 (2011-07-09 patchlevel 290) [i386-darwin10.7.1]
– INSTALLATION DIRECTORY: /Users/hrastogi/.rvm/gems/ruby-1.9.2-p290
– RUBY EXECUTABLE: /Users/hrastogi/.rvm/rubies/ruby-1.9.2-p290/bin/ruby
– EXECUTABLE DIRECTORY: /Users/hrastogi/.rvm/gems/ruby-1.9.2-p290/bin
– RUBYGEMS PLATFORMS:
– ruby
– x86-darwin-10
– GEM PATHS:
– /Users/xxxx/.rvm/gems/ruby-1.9.2-p290
– /Users/xxxx/.rvm/gems/ruby-1.9.2-p290@global
– GEM CONFIGURATION:
– :update_sources =&gt; true
– :verbose =&gt; true
– :benchmark =&gt; false
– :backtrace =&gt; false
– :bulk_threshold =&gt; 1000
– REMOTE SOURCES:
http://rubygems.org/

Gem is installed in multiple paths. Try deleting manually from one of the path

gem uninstall rake -i /Users/xxxx/.rvm/gems/ruby-1.9.2-p290@global