Ruby on Rails - Render JSON
I have the following controller:
@moulding = Moulding.find( params[:id].split(","), :select => 'id, cost, width' )
@mount = MaterialCost.find(1).cost_per_square_mm
@glass = MaterialCost.find(2).cost_per_square_mm
@backing_board = MaterialCost.find(3).cost_per_square_mm
@vat = AppOption.find( 1, :select => 'value' )
@wastage = AppOption.find( 2, :select => 'value' )
@markup = AppOption.find( 3, :select => 'value' )
respond_to do |format|
format.json { render :json => { :moulding => @moulding, :mount => @mount, :glass => @glass, :backing_board => @backing_board, :vat => @vat, :wastage => @wastage, :markup => @markup } }
end
The JSON output is as follows:
{"moulding":[{"moulding":{"cost":"3.1","id":2,"width":45}},{"moulding":{"cost":"1.5","id":4,"width":30}},{"moulding":{"cost":"2.1","id":6,"width":50}}],"mount":"0.00000246494303242769","glass":"0.0000032426589803639","backing_board":"0.00000135110790848496","vat":{"app_option":{"value":"17.5"}},"wastage":{"app_option":{"value":"20"}},"markup":{"app_option":{"value":"3"}}}
I would like JSON to be in the following format:
{"mouldings":[{"2":{"cost":"3.1","width":45}},{"4":{"cost":"1.5","width":30}},{"6":{"cost":"2.1","width":50}}],"mount":"0.00000246494303242769","glass":"0.0000032426589803639","backing_board":"0.00000135110790848496","vat":{"app_option":{"value":"17.5"}},"wastage":{"app_option":{"value":"20"}},"markup":{"app_option":{"value":"3"}}}
The reason I want to do this is because I can extract data for a specific mouldingon idfrom a JSON string. How to reformat processed JSON?
In my initial answer, I made the erroneous assumption that @moulding was the only object when in fact it was a collection of objects. In this case, the answer will work. To do what you want for molding, you have to repackage a set of objects. It will look like this:
@moulding.collect! do |moulding|
{ moulding.id => {:cost=>moulding.cost, :width=>moulding.width}}
end
respond_to do |format|
format.json { render :json => { :moulding => @moulding, :mount => @mount, :glass => @glass, :backing_board => @backing_board, :vat => @vat, :wastage => @wastage, :markup => @markup } }
end
collect , , . collect! ( , ). , .
, . , .
:
, :moulding . :
format.json { render :json => { @moulding.id => @moulding, :mount => @mount, :glass => @glass, :backing_board => @backing_board, :vat => @vat, :wastage => @wastage, :markup => @markup } }
, , .
.. @ , . .