我有以下的控制器代碼:Ruby on Rails的 - JSON格式
def calculate_quote
@mouldings = Moulding.find(params[:id].split(","), :select => 'id, cost, width')
@mouldings.collect! do |moulding|
{ "moulding_id_#{moulding.id}" => { :cost => moulding.cost, :width => moulding.width } }
end
@material_costs = MaterialCost.all
@material_costs.collect! do |material_cost|
{ material_cost.material.gsub(" ", "_").downcase => { :cost => material_cost.cost_per_square_mm } }
end
@app_options = AppOption.all
@app_options.collect! do |app_option|
{ app_option.name.gsub(" ", "_").downcase => { :value => app_option.value } }
end
respond_to do |format|
format.json { render :json => { :mouldings => @mouldings, :material_costs => @material_costs, :app_options => @app_options } }
end
end
而這給了我下面的JSON輸出:
{"mouldings":[{"moulding_id_2":{"cost":"3.1","width":45}},{"moulding_id_4":{"cost":"1.5","width":30}},{"moulding_id_6":{"cost":"2.1","width":50}}],"material_costs":[{"mountboard":{"cost":"0.00000246494303242769"}},{"glass":{"cost":"0.0000032426589803639"}},{"backing_board":{"cost":"0.00000135110790848496"}}],"app_options":[{"vat":{"value":"17.5"}},{"wastage":{"value":"20"}},{"markup":{"value":"3"}}]}
我想格式化JSON輸出,所以我可以使用jQuery使用以下語法來提取數據:
data.mouldings.moulding_id_2.cost
如何更改控制器以實現這個?
我想使用JSON訂閱源中的所有數據在客戶端上執行計算。使用`data.mouldings.moulding_id_2.cost`和`data.material_costs.mountboard.cost`這樣的數據來獲取數據,而不是通過數據做多重循環確實不容易? – freshest 2010-12-08 13:15:14