我正在開發一個使用Sinatra的小應用程序。到目前爲止這麼好,但我有一個非常小的問題,我不明白爲什麼會發生這種情況。在數組上調用to_json返回的內容與在對象中調用to_json不同
我有一個類注意使用自定義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\"}"
如果我增加一個陣列內的對象並致電該陣列的__son
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寶石)
謝謝。
仍然返回我在我的問題:( – Andres
@Andres對不起,我有一個錯字,現在試試:) – Agis