我有一个查找操作的ActiveRecord结果:
tasks_records = TaskStoreStatus.find(
:all,
:select => "task_id, store_name, store_region",
:conditions => ["task_status = ? and store_id = ?", "f", store_id]
)
现在我想将这个结果转换成一个散列数组,如下所示:
[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
以供我的应用程序接口响应使用。我该怎么做呢?
发布于 2013-03-26 03:40:24
as_json
您应该使用as_json
方法,该方法将ActiveRecord对象转换为Ruby散列,而不管其名称
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结果转换为数组,因此对于您的示例:
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
如果您想要一个丑陋的Rails v2.3之前的解决方案
JSON.parse(tasks_records.to_json) # please don't do it
发布于 2016-07-19 15:36:06
有可能吗?
result.map(&:attributes)
如果您需要symbols键:
result.map { |r| r.attributes.symbolize_keys }
发布于 2016-06-21 03:33:45
对于当前的ActiveRecord (4.2.4+),Result
对象上有一个方法to_hash
,它返回一个散列数组。然后,您可以在其上映射并转换为符号化的哈希:
# 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"},
...
]
https://stackoverflow.com/questions/15427936
复制相似问题