如何将activerecord结果转换为包含root的哈希数组

时间:2013-06-13 15:21:23

标签: activerecord hash

假设你想要

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

就像to_json(:root => true)那样

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

1 个答案:

答案 0 :(得分:9)

as_json

records.as_json(:root => true)

serializable_hash

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

这不适用于嵌套对象