【问题标题】:Override as_json or to_json model class name覆盖 as_json 或 to_json 模型类名
【发布时间】:2010-03-31 21:08:05
【问题描述】:

我想在 AR 模型上调用 to_json 时修改类名。

Book.first.to_json
 #=> "{\"book\":{\"created_at\":\"2010-03-23 

Book.first.to_json(:root => 'libro')
 #=> "{\"libro\":{\"created_at\":\"2010-03-23 

有没有办法做到这一点?

【问题讨论】:

  • 我不知道覆盖 to_json 但是你可以设置 ActiveRecord::Base.include_root_in_json = false 并且它不会输出根节点,然后你可以添加任何你喜欢的根节点。跨度>

标签: ruby-on-rails json activerecord


【解决方案1】:

要与 Rails 3 兼容,请覆盖 as_json 而不是 to_json。它是在 2.3.3 中引入的:

def as_json(options={})
  { :libro => { :created_at => created_at } }
end

确保ActiveRecord::Base.include_root_in_json = false。调用to_json时,后台as_json用于构建数据结构,ActiveSupport::json.encode用于将数据编码成JSON字符串。

【讨论】:

    【解决方案2】:

    至少从 3.0.5 开始,您现在可以选择将 :root 选项传递给 to_json 调用。这里是现在活动记录上的 as_json 方法的来源。

    def as_json(options = nil)
        hash = serializable_hash(options)
    
        if include_root_in_json
          custom_root = options && options[:root]
          hash = { custom_root || self.class.model_name.element => hash }
        end
    
        hash
    end
    

    所以要使用这个@obj.to_json(:root => 'custom_obj')

    【讨论】:

      【解决方案3】:

      您可以覆盖模型中的默认 to_json 方法,构建所需属性的散列,然后在其上调用散列的 to_json 方法。

      class Book < ActiveRecord::Base
      
        def to_json
          { :libro => { :created_at => created_at } }.to_json
        end
      
      end
      
      #=> "{\"libro\":{\"created_at\":\"2010-03-26T13:45:28Z\"}}"
      

      或者如果你想要所有的记录属性...

      def to_json
        { :libro => self.attributes }.to_json
      end
      

      【讨论】:

        猜你喜欢
        • 2012-11-15
        • 2015-10-14
        • 2011-12-02
        • 2011-04-29
        • 1970-01-01
        • 2011-07-08
        • 1970-01-01
        • 2011-06-26
        • 1970-01-01
        相关资源
        最近更新 更多