1

I am trying to post some data to a web service from jQuery:

  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');
  });

Rails:

  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:"

and the params look like this:

enter image description here

however, it is erroring out with:

  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'

And I'm not sure why it's treating the key of the array as output. How would I fix this?

1 Answer 1

1

If you want tmp_line_item to return {"name"=>"jon"} and {"name"=>"joan"}, then try:

line_items.each_with_index do |(k, tmp_line_item), idx|
  ...
Sign up to request clarification or add additional context in comments.

2 Comments

weird, why is that? Is that a Rails issue - I thought it would go in a straight array.
@timpone Here's a (brief) explanation I found: makandracards.com/makandra/…. Is that what you're wondering about?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.