如何将 ActiveRecord 结果转换为哈希数组 [英] How to convert ActiveRecord results into an array of hashes
问题描述
我有一个查找操作的 ActiveRecord 结果:
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" }
这样我就可以遍历数组并向哈希添加更多元素,然后将结果转换为 JSON
以供 API 响应使用.我该怎么做?
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?
推荐答案
as_json
你应该使用 as_json
方法将 ActiveRecord 对象转换为 Ruby Hashes,尽管它的名字是
as_json
You should use 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
您还可以使用 serializable_hash
将任何 ActiveRecord 对象转换为哈希,并且您可以使用 to_a
将任何 ActiveRecord 结果转换为数组,例如:
serializable_hash
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
如果你想要一个在 v2.3 之前的 Rails 丑陋的解决方案
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
这篇关于如何将 ActiveRecord 结果转换为哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!