简体   繁体   中英

Rails converting Javascript array to Hash?

I JS I send this to rails:

[{name: "Jon"}, {name: "Jane"}]

I expect Rails/Ruby to interpret it into the same structure, but instead it converts it to a hash like this:

{ "0" => {"name" => "Jon"}, "1" => {"name" => "Jane"} }

Any idea why this happens, or how to prevent it?

You're not actually sending [{name: "Jon"}, {name: "Jane"}] , you're sending "[{name: "Jon"}, {name: "Jane"}]" so rails has to convert it to something or else you'd be doing some messy regex's to get at the data you want. So rails converts it to a HashWithIndifferentAccess Object for you. I highly doubt you want to hack at rails internals, so why not just parse your code the way rails presents it instead of coercing it into another format?

That's a correct behaviour. If you're interested in sending Array as parameters, you have to use some_field_name[] type of field instead of simple "field_name" in javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM