简体   繁体   English

Rails将Javascript数组转换为Hash?

[英]Rails converting Javascript array to Hash?

I JS I send this to rails: 我用JS将其发送到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: 我希望Rails / Ruby可以将其解释为相同的结构,但可以将其转换为如下所示的哈希值:

{ "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. 您实际上不是在发送[{name: "Jon"}, {name: "Jane"}] ,而是在发送"[{name: "Jon"}, {name: "Jane"}]"所以rails将其转换为其他内容,否则您将需要进行一些麻烦的正则表达式以获取所需的数据。 So rails converts it to a HashWithIndifferentAccess Object for you. 因此,Rails会为您将其转换为HashWithIndifferentAccess对象 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? 我非常怀疑您是否想破解Rails的内部结构,那么为什么不只按照Rails呈现代码的方式解析您的代码,而不是将其强制转换为另一种格式?

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. 如果您有兴趣将Array作为参数发送,则必须使用some_field_name[]类型的字段,而不是JavaScript中的简单“ field_name”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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