如何ActiveRecord的成果转化为哈希数组,包括根 [英] How to convert activerecord results into an array of hashes including root

查看:143
本文介绍了如何ActiveRecord的成果转化为哈希数组,包括根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,你想

 记录= Model.all
records.to_a.map {| M | m.serializable_hash(:根=>真)}
 

就像 to_json(:根=>真)确实

  [
  {
    模型: {
      attribute_1:_1,
      attribute_2:_2,
    }
  }
  ...
]
 

解决方案

as_json

  records.as_json(:根=>真)
 

serializable_hash

  records.to_a.map(){| x |
  {x.class.model_name.element => x.serializable_hash()}
}
 

与嵌套对象尽管

这是行不通的

Let's say you want to

records = Model.all
records.to_a.map{|m| m.serializable_hash(:root => true)}

just like to_json(:root => true) does

[
  {
    "model": {
      "attribute_1": "value_1",
      "attribute_2": "value_2",
    }
  }
  ...
]

解决方案

as_json

records.as_json(:root => true)

serializable_hash

records.to_a.map() {|x| 
  { x.class.model_name.element => x.serializable_hash() } 
}

This will not work with nested objects though

这篇关于如何ActiveRecord的成果转化为哈希数组,包括根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆