Skip to content

Instantly share code, notes, and snippets.

@gorenje
Created October 13, 2010 13:13
Show Gist options
  • Save gorenje/624020 to your computer and use it in GitHub Desktop.
Save gorenje/624020 to your computer and use it in GitHub Desktop.
ActiveResource/Rails confuses parameter values when deserializing.
Using ActiveResource 2.3.8 (AccountUpdate is ActiveResource class) with ruby 1.8.7.
The REST server is a Rails 3.0.0beta4 running ruby 1.9.2.
Set up two hashes, one containing an _id value, the other not. The Hash with the
_id field has a :name value of "hello", the other hash contains only the :name field
with value fubar.
=============
ruby-1.8.7-head > account1 = {"_id" => "4cb5ab241ba260859f000002", :name => "hello"}
=> {"_id"=>"4cb5ab241ba260859f000002", :name=>"hello"}
ruby-1.8.7-head > account2 = {:name => "fubar"}
=> {:name=>"fubar"}
### Request one: array ordering: account1, account2
ruby-1.8.7-head > AccountUpdate.post("import", :accounts => [account1, account2]).body
=> "{"failed_count":0}"
### Request two: array ordering is reversed.
ruby-1.8.7-head > AccountUpdate.post("import", :accounts => [account2, account1]).body
=> "{"failed_count":0}"
=============
The only difference between the two requests is the ordering of the account variables.
=============
### Request one
Started POST "/account_updates/import.json?accounts%5B%5D%5B_id%5D=4cb5ab241ba260859f000002&accounts%5B%5D%5Bname%5D=hello&accounts%5B%5D%5Bname%5D=fubar" for 127.0.0.1 at 2010-10-13 15:10:13 +0200
Processing by AccountUpdatesController#import as JSON
Parameters: {"accounts"=>[{"_id"=>"4cb5ab241ba260859f000002", "name"=>"hello"}, {"name"=>"fubar"}]}
### Request two
Started POST "/account_updates/import.json?accounts%5B%5D%5Bname%5D=fubar&accounts%5B%5D%5B_id%5D=4cb5ab241ba260859f000002&accounts%5B%5D%5Bname%5D=hello" for 127.0.0.1 at 2010-10-13 15:10:17 +0200
Processing by AccountUpdatesController#import as JSON
Parameters: {"accounts"=>[{"name"=>"fubar", "_id"=>"4cb5ab241ba260859f000002"}, {"name"=>"hello"}]}
=============
Point being that when rails deserializes the request, it gets confused and
assigns the _id value to the wrong hash (i.e. the hash with name value of fubar).
This can be seen in the second request parameters value:
{"accounts"=>[{"name"=>"fubar", "_id"=>"4cb5ab241ba260859f000002"}, {"name"=>"hello"}]}
Suddenly the hash with name=>fubar has an _id value!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment