本文介绍了如何ActiveRecord的结果转换成散列的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动记录结果作为查找操作的结果。

I have a active record result as a 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 a array of hashes like the one 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" }

,这样我就可以遍历数组,并添加更多的元素,哈希值,然后而后再将结果转换成 JSON 我的API响应!

推荐答案

您应该使用 as_json 法至极转换ActiveRecord对象红宝石哈希尽管它的名字

as_json

You should use as_json method wich convert 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

您也可以将任何ActiveRecord对象以哈希与 serializable_hash ,你可以在任何ActiveRecord的结果转换为用 to_a ,所以你的例子:

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的结果转换成散列的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:54