Search code examples
ruby-on-railsrubyunirest

Passing complex object to rails action via Unirest


I have a simple controller:

class ApplicationController < ActionController::Base
  def test_action
    render plain: "OK"
  end
end

And I'm posting to the action via a separate ruby file using Unirest:

require 'unirest'

resp = Unirest.post "localhost:3000/test_action.json", 
                    headers:{ "Accept" => "application/json" }, 
                    parameters:{ foo: 1, my_list: [{foo: 1}, {foo: 2}] }

puts resp.body

When I run this I see the following in my rails console:

Parameters: {"foo"=>"1", "my_list"=>{"foo"=>"2"}}

Why is the first item in my_list missing? How can I get it to appear? Should I be using something other than Unirest for this?


Solution

  • When working with hashes the second key value will overwrite the first. foo: 2 gets read last and is the last assignment for foo. If you want the first item to appear you should rename it to [{"foo1":"1"}, {"foo2": 2}]