How to convert activerecord results to a hash array, including root

Let's say you want

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", } } ... ] 
+6
activerecord hash
Jun 13 '13 at 15:21
source share
1 answer

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

+9
Jun 13 '13 at 15:22
source share



All Articles