How to convert activerecord results to a hash array

I have an active record result as a result of a search operation

tasks_records = TaskStoreStatus.find(:all,:select => "task_id, store_name, store_region", :conditions => ["task_status = ? and store_id= ?","f" ,store_id]) 

Now I want to convert these results to an array of hashes, as shown below

 [0] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } [1] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } [2] -> { :task_d => 10, :store_name=> "Koramanagala", :store_region=> "India" } 

So, I can iterate through the array and add additional elements to the hashes, and then convert the result to JSON for my API response!

+68
arrays activerecord hash
Mar 15 '13 at 8:40
source share
4 answers

as_json

You should use the as_json method, which converts ActiveRecord objects to Ruby Hashes, despite its name

 tasks_records = TaskStoreStatus.all tasks_records = tasks_records.as_json # You can now add new records and return the result as json by calling `to_json` tasks_records << TaskStoreStatus.last.as_json tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" } tasks_records.to_json 

serializable_hash

You can also convert any ActiveRecord objects to Hash using serializable_hash , and you can convert any ActiveRecord results to Array using to_a , so for your example:

 tasks_records = TaskStoreStatus.all tasks_records.to_a.map(&:serializable_hash) 

And if you need an ugly solution for Rails before v2.3

 JSON.parse(tasks_records.to_json) # please don't do it 
+136
Mar 25 '13 at 19:40
source share
— -

May be?

 result.map(&:attributes) 

If you need characters:

 result.map { |r| r.attributes.symbolize_keys } 
+17
Jul 19 '16 at 7:36
source share

In response to the Dom comment above: How do I include a type name in serialization?

Using the to_json or as_json approach, just include the following code snippet in your model to override the default behavior:

 def as_json super.as_json {methods: [:type]} end def type self.model_name.name end 
+6
Jan 16 '15 at 10:28
source share

For the current ActiveRecord (4.2.4+), there is a to_hash method of the to_hash object, which returns an array of hashes. Then you can move it and convert it to symbolized hashes:

 # Get an array of hashes representing the result (column => value): result.to_hash # => [{"id" => 1, "title" => "title_1", "body" => "body_1"}, {"id" => 2, "title" => "title_2", "body" => "body_2"}, ... ] result.to_hash.map(&:symbolize_keys) # => [{:id => 1, :title => "title_1", :body => "body_1"}, {:id => 2, :title => "title_2", :body => "body_2"}, ... ] 

See the ActiveRecord :: Result docs for more details .

+3
Jun 20 '16 at 19:33
source share



All Articles