Ruby on rails Rails 3.2:使用单个根元素将ActiveRecord对象的集合序列化为JSON
如何让ActiveRecords集合序列化为一个JSON对象,其中包含一个Collections元素数组的单个根元素 我们刚刚从Rails 3.0.10升级到Rails 3.2,在ActiveRecord对象集合序列化为JSON的方式上遇到了问题 我读过一些书,知道用Ruby on rails Rails 3.2:使用单个根元素将ActiveRecord对象的集合序列化为JSON,ruby-on-rails,json,Ruby On Rails,Json,如何让ActiveRecords集合序列化为一个JSON对象,其中包含一个Collections元素数组的单个根元素 我们刚刚从Rails 3.0.10升级到Rails 3.2,在ActiveRecord对象集合序列化为JSON的方式上遇到了问题 我读过一些书,知道用来处理json可能是个坏主意,我们会尽快解决这个问题,但在此期间,我正在寻找最快的方法来修复我的代码,所以它会像以前那样做,因为这些更改破坏了我们的API 我们有一个类型为Form的ActiveRecord对象集合,这些对象在“索引
来处理json
可能是个坏主意,我们会尽快解决这个问题,但在此期间,我正在寻找最快的方法来修复我的代码,所以它会像以前那样做,因为这些更改破坏了我们的API
我们有一个类型为Form的ActiveRecord对象集合,这些对象在“索引”操作中以JSON的形式返回,代码如下:
def index # in our FormsController
# get our "records" collection from the database
respond_to do |format|
yield(format) if block_given?
# other formats excluded for simplicity
format.json {
records = records.call if records.is_a?(Proc)
render :json => records.to_json(serialize_records_options), :layout => false
}
end
end
# These are in ApplicationController
def serialize_options
(self.class.serialize_options if self.class.respond_to? :serialize_options) || {}
end
def serialize_records_options
options = serialize_options.clone
options[:root] = (options[:root].pluralize if options[:root]) || controller_name
options[:indent] ||= 2
options
end
问题在于,这用于序列化为:
{
"total_entries": 2,
"total_pages": 1,
"forms": [{
"form": {
... attributes ...
}
},
{
"form": {
... attributes ...
}
}],
"per_page": 5,
"current_page": 1
}
现在序列化为:
[{
"forms": {
... attributes of form 1 ...
}
},
{
"forms": {
... attributes of form 2 ...
}
},
{
... more forms ...
}]
我们的客户端应用程序甚至不承认该格式是有效的JSON对象。有没有办法让它以原始格式输出?除了升级Rails及其依赖项之外,我们没有更改任何序列化代码。我们的捆绑包中有以下JSON gem:
$ bundle show | grep json
* json (1.7.3)
* jsonpath (0.5.0)
* multi_json (1.3.5)
提前谢谢!这是一个奇怪的问题。我想不需要
到_json
,我想:json=>
会将其转换为json对象谢谢。我已经看到了这一点,但它仍然无法解决我们的问题,无法通过单个根元素将集合输出为JSON对象。您可以看到以前的响应和现在的响应。最大的区别在于整个集合位于一个JSON对象中,该对象具有根元素“forms”。JFI是否设置了ActiveRecord::Base.include\u root\u in\u JSON=true