【问题标题】:Calling to_json on array returns something different from calling to_json in object在数组上调用 to_json 会返回与在对象中调用 to_json 不同的东西
【发布时间】: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_atcreated_at

我做错了什么? (顺便说一句,我正在使用 json gem)

谢谢。

【问题讨论】:

    标签: ruby json sinatra


    【解决方案1】:

    将您的to_json 方法重命名为as_json,删除哈希上的.to_json,它应该可以工作。

    def as_json(options={})
      {
       'id' => self.id,
       'name' => self.name,
       'body' => self.body,
      }
    end
    

    【讨论】:

      【解决方案2】:

      您可以在将记录添加到数组之前对其进行序列化:

      array = []
      array << Note.first.to_json
      array.to_json
      

      【讨论】:

      • 那仍然返回我的问题:(
      • @Andres 抱歉,我打错了。立即尝试:)
      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多