Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAILS3: to_JSON with multiple objects and includes

def list
    @rings = Ring.order("RAND()")
    #JSON RENDERING
    render :json => @rings.to_json(:include => [:variations, :stones]), :callback => params[:callback]
end

def show
    @showring = Ring.includes(:stones, :variations).find(params[:id])
    @other_rings = Ring.select([:id, :stone_count]).where(:style_number => @showring.style_number).reject{ |ring| ring == @showring}
    #JSON RENDERING
    render :json => {@showring.to_json(:include =>[:variations, :stones]), :other_rings => @other_rings}, :callback => params[:callback]
end

My list view rendering works fine, but when i want to do a show view, with two objects, and showring with includes won't render proper JSON. It is quoting everything in the object with the includes...

JSON output looks like this:

showring => "{"available":"yes","eng...9","stone_y":"149.4"}]}"

other_rings => properly rendered object


On a seperate note, if i have already added the includes to @rings object, why do i then again have to add the association in the "to_json" method?

like image 903
Joel Grannas Avatar asked Mar 02 '26 13:03

Joel Grannas


2 Answers

When you do

render :json => {:show_ring => @showring.to_json(:include =>[:variations, :stones]), :other_rings => @other_rings}

Rails is converting @showring to json (ie getting back a string representation), i.e. the value is the string literal. Instead do

render :json => {:show_ring => @showring.as_json(:include =>[:variations, :stones]), :other_rings => @other_rings}

as_json does all the work of turning the object into a hash but without the final step of turning into a string

like image 119
Frederick Cheung Avatar answered Mar 04 '26 01:03

Frederick Cheung


if you are going to invest more time in building more JSON objects, you should look into a gem called rabl. It makes building JSON very simple, good for customization which then is good for building API.

like image 27
YaBoyQuy Avatar answered Mar 04 '26 01:03

YaBoyQuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!