【发布时间】:2014-01-18 12:05:05
【问题描述】:
我正在使用 Sinatra 开发一个小型应用程序。到目前为止一切顺利,但我遇到了一个非常小的问题,我不明白为什么会这样。
我有一个带有自定义 to_json 的课堂笔记:
class Note < ActiveRecord::Base
#id
#name
#body
#created_at
#updated_at
def to_json(options={})
{ 'id' => self.id,
'name' => self.name,
'body' => self.body,
}.to_json
end
end
如果我打电话:
Note.first.to_json
返回:
=> "{\"id\":1,\"name\":\"this is the name\",\"body\":\"this is the body\"}"
如果我在数组中添加对象并调用该数组的 to_json
array = Array.new
array.push Note.first
array.to_json
返回:
=> "[{\"id\":1,\"name\":\"this is the name\",\"body\":\"this is the body\",\"updated_at\":\"2014-01-17T22:00:45-03:00\",\"created_at\":\"2013-04-17T21:21:20-03:00\"}]"
所以 Note 类的 to_json 没有被调用,因为我仍然得到 updated_at 和 created_at
我做错了什么? (顺便说一句,我正在使用 json gem)
谢谢。
【问题讨论】: