I have an ActiveRecord result of a find 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 this results into an array of hashes like this:
[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 that I will be able to iterate through the array and to add more elements to hashes and later to convert the result into JSON
for my API response. How can I do this?
May be?
If you need symbols keys:
as_json
You should use
as_json
method which converts ActiveRecord objects to Ruby Hashes despite its nameserializable_hash
You can also convert any ActiveRecord objects to a Hash with
serializable_hash
and you can convert any ActiveRecord results to an Array withto_a
, so for your example :And if you want an ugly solution for Rails prior to v2.3
For current ActiveRecord (4.2.4+) there is a method
to_hash
on theResult
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:See the ActiveRecord::Result docs for more info.