簡體   English   中英

Ruby on Rails-JSON格式

[英]Ruby on Rails - JSON Format

我有以下控制器代碼:

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

我將如何更改控制器以實現此目的?

讓我們嘗試重新考慮構建數據的方式。 在我看來,將id用作對象索引並不是很有意義。 相反,為什么不做這樣的事情:

@mouldings = Moulding.find( params[:id].split(","), :select => 'id, cost, width' )
@mouldings.collect! do |moulding|
  { :id => moulding.id, :cost => moulding.cost, :width => moulding.width }
end

這樣,您應該有一個對象數組,其中包含該成型所需的所有數據。 然后,在jQuery中,您可以遍歷此數組並獲取所需的所有信息,如下所示:

$.each(data.mouldings, function(index, moulding) {
    alert("This moulding has an id of " + moulding.id + " and costs " + moulding.cost);
});

我認為這比顯式調用更有意義:

數據造型。 moulding_id_2 .cost

如果您想找到確切的moulding_id#2,則應該像上面顯示的那樣遍歷數據集,並執行如下檢查:

if (moulding.id == 2) {//do something};

目前,模制品是單例哈希的列表。 您希望它是一個將哈希ID映射到詳細哈希的單個哈希。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM