Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",
    }
  }
  ...
]
like image 765
hdorio Avatar asked Jun 13 '13 15:06

hdorio


1 Answers

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

like image 73
hdorio Avatar answered Sep 21 '22 11:09

hdorio