繁体   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