5
我有以下的控制器:Ruby on Rails的 - 渲染JSON
@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
的JSON輸出如下:
{"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"}}}
我想JSON是在以下格式:
{"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"}}}
我想這樣做的原因是我可以通過提取特定moulding
的數據來自JSON字符串的。我如何重新格式化呈現的JSON?
@Berin Loritsch - 使用`@ moulding.id`會給出錯誤`undefined method`id'`。 – freshest 2010-12-07 15:52:18