如何ActiveRecord的结果转换成散列的数组数组、转换成、结果、ActiveRecord

由网友(你是我一生的赌注ゞ)分享简介:我有一个活动记录结果作为查找操作的结果。I have a active record result as a result of a find operationtasks_records = TaskStoreStatus.find(:all,:select => "task_id, store_name, st...

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

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

yii active record多表关联查询的一些细节

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