语法问题迭代Rails中的项目数组

时间:2015-10-21 22:59:31

标签: jquery ruby-on-rails

我正试图从jQuery向web服务发布一些数据:

  var jtvals={};
  jtvals['line_items']=[];
  var g={"name":"jon"};
  var h={"name":"joan"};

  jtvals['line_items'].push(g);
  jtvals['line_items'].push(h);

  $.ajax({
    url: '/arc/v1/api/calculate_line_items',
    type: 'POST',
    data: jtvals,
    dataType: 'json'
  }).done(function(r){
    alert('this is finished');
  });

滑轨:

  def calculate_line_items
    line_items=params[:line_items]
    puts line_items
    puts line_items.count
    puts "DO LOOP:"

    line_items.each_with_index do |tmp_line_item, idx|
        puts "idx:"
        puts idx

        puts "about to give you:"
        puts tmp_line_item
        puts "after giving you:"

并且params看起来像这样:

enter image description here

然而,错误的是:

  Parameters: {"line_items"=>{"0"=>{"name"=>"jon"}, "1"=>{"name"=>"joan"}}}
{"0"=>{"name"=>"jon"}, "1"=>{"name"=>"joan"}}
2
DO LOOP:
idx:
0
about to give you:
0
{"name"=>"jon"}
after giving you:
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms)

TypeError (no implicit conversion of String into Integer):
  app/controllers/api_orders_controller.rb:41:in `[]'
  app/controllers/api_orders_controller.rb:41:in `block in calculate_line_items'
  app/controllers/api_orders_controller.rb:33:in `each_with_index'
  app/controllers/api_orders_controller.rb:33:in `calculate_line_items'

我不确定为什么它将数组的键视为输出。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果您希望tmp_line_item返回{"name"=>"jon"}{"name"=>"joan"},请尝试:

line_items.each_with_index do |(k, tmp_line_item), idx|
  ...