[英]syntax issue iterating through array of items in 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:"
和參數看起來像這樣:
但是,它出現以下錯誤:
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'
而且我不確定為什么將數組的鍵作為輸出。 我該如何解決?
如果您希望tmp_line_item
返回{"name"=>"jon"}
和{"name"=>"joan"}
,請嘗試:
line_items.each_with_index do |(k, tmp_line_item), idx|
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.