Rails to_json与收到的JSON不同

时间:2012-05-09 17:41:47

标签: json ruby-on-rails-3.1 restkit

我试图弄清楚为什么服务器上的JSON与使用Restkit在我的移动应用程序中收到的不同。当我用puts @items.to_json查看对象的JSON表示时,我得到以下内容:

[{"item":{"created_at":"2012-04-19T19:42:44Z","id":4,"json_event_id":null,"name":"Biz Cards","theme_id":null,"updated_at":"2012-04-19T19:42:44Z","url":"","user_id":3}},
 {"item":{"created_at":"2012-04-20T19:37:33Z","id":5,"json_event_id":null,"name":"Hummus","theme_id":null,"updated_at":"2012-04-20T19:37:33Z","url":"","user_id":3}},
 {"item":{"created_at":"2012-04-20T20:01:57Z","id":7,"json_event_id":null,"name":"Wine","theme_id":null,"updated_at":"2012-04-20T20:01:57Z","url":"","user_id":3}},
 {"item":{"created_at":"2012-04-25T19:57:33Z","id":9,"json_event_id":null,"name":"this","theme_id":null,"updated_at":"2012-04-25T19:57:33Z","url":"","user_id":3}}]

但是,当我查看客户端收到的JSON时,我得到一个包含所有空值的新JSON元素,包括ID(此处的最后一个元素):

[{"item":{"created_at":"2012-04-19T19:42:44Z","id":4,"json_event_id":null,"name":"Biz Cards","theme_id":null,"updated_at":"2012-04-19T19:42:44Z","url":"","user_id":3}},
 {"item":{"created_at":"2012-04-20T19:37:33Z","id":5,"json_event_id":null,"name":"Hummus","theme_id":null,"updated_at":"2012-04-20T19:37:33Z","url":"","user_id":3}}, 
 {"item":{"created_at":"2012-04-20T20:01:57Z","id":7,"json_event_id":null,"name":"Wine","theme_id":null,"updated_at":"2012-04-20T20:01:57Z","url":"","user_id":3}}, 
 {"item":{"created_at":"2012-04-25T19:57:33Z","id":9,"json_event_id":null,"name":"this","theme_id":null,"updated_at":"2012-04-25T19:57:33Z","url":"","user_id":3}}, 
 {"item":{"created_at":null,"id":null,"json_event_id":null,"name":null,"theme_id":null,"updated_at":null,"url":null,"user_id":3}}]

为什么@items.to_json会返回与format.json { render json: @items }不同的JSON,如何回复正确的@items.to_json

修改 这是填充@items的代码:

@items = current_user.items

修改 这似乎只有在我基于current_user填充@items时才会发生:

@items = current_user.items

当我完成所有操作时,没有其他空对象:

@items = Item.all

0 个答案:

没有答案