How to convert activerecord results into an array of hashes including root

£可爱£侵袭症+ 提交于 2019-12-10 04:21:10

问题


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",
    }
  }
  ...
]

回答1:


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



来源:https://stackoverflow.com/questions/17090891/how-to-convert-activerecord-results-into-an-array-of-hashes-including-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!