Ruby on Rails - JSON格式

时间:2010-12-08 00:18:45

标签: jquery 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

如何更改控制器以实现此目的?

2 个答案:

答案 0 :(得分:1)

让我们尝试重新思考您构建数据的方式。在我看来,使用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);
});

我认为这比明确调用更有意义:

  

data.mouldings。的 moulding_id_2 。成本

如果你想找到确切的moulding_id#2,那么你应该如上所示迭代你的数据集,并执行如下检查:

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

答案 1 :(得分:0)

目前,造型是一系列单身哈希。您希望它是单个哈希映射ID到细节哈希。