Rails将空数组转换为请求参数中的nil [英] Rails converts empty arrays into nils in params of the request
问题描述
我的应用程序中有一个Backbone模型,它不是典型的平面对象,它是一个很大的嵌套对象,我们将嵌套部分存储在MySQL数据库的TEXT列中.
I have a Backbone model in my app which is not a typical flat object, it's a large nested object and we store the nested parts in TEXT columns in a MySQL database.
我想在Rails API中处理JSON编码/解码,以便从外部看来,即使部分存储为字符串化JSON文本,您也可以POST/GET这个大嵌套的JSON对象.
I wanted to handle the JSON encoding/decoding in Rails API so that from outside it looks like you can POST/GET this one large nested JSON object even if parts of it are stored as stringified JSON text.
但是,我遇到了一个问题,其中Rails神奇地将空数组转换为nil
值.例如,如果我发布此信息:
However, I ran into an issue where Rails magically converts empty arrays to nil
values. For example, if I POST this:
{
name: "foo",
surname: "bar",
nested_json: {
complicated: []
}
}
我的Rails控制器看到以下内容:
My Rails controller sees this:
{
:name => "foo",
:surname => "bar",
:nested_json => {
:complicated => nil
}
}
所以我的JSON数据已被更改..
And so my JSON data has been altered..
以前有人遇到过这个问题吗?为什么Rails会修改我的POST数据?
Has anyone run into this issue before? Why would Rails be modifying my POST data?
更新
他们在这里做这件事:
https://github.com/rails/rails /blob/master/actionpack/lib/action_dispatch/http/request.rb#L288
这是〜他们这样做的原因:
And here is ~why they do it:
https://github.com/rails/rails/pull/8862
所以现在的问题是,如何在嵌套的JSON API情况下最好地解决这个问题?
So now the question is, how to best deal with this in my nested JSON API situation?
推荐答案
经过大量搜索,我发现您从Rails 4.1开始,可以完全使用以下方法跳过deep_munge功能"
After much searching, I discovered that you starting in Rails 4.1 you can skip the deep_munge "feature" completely using
config.action_dispatch.perform_deep_munge = false
我找不到任何文档,但是您可以在这里查看此选项的介绍: https://github.com/rails/rails/commit/e8572cf2f94872d81e7145da31d55c6e1b074247
I could not find any documentation, but you can view the introduction of this option here: https://github.com/rails/rails/commit/e8572cf2f94872d81e7145da31d55c6e1b074247
这样做有可能的安全风险,请在此处记录: https://groups. google.com/forum/#!topic/rubyonrails-security/t1WFuuQyavI
There is a possible security risk in doing so, documented here: https://groups.google.com/forum/#!topic/rubyonrails-security/t1WFuuQyavI
这篇关于Rails将空数组转换为请求参数中的nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!