我有一个查找操作的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
以获取API响应。我怎么能这样做?
答案 0 :(得分:174)
您应该使用as_json
方法将ActiveRecord对象转换为Ruby Hashes,尽管名称为
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对象转换为哈希,并且可以将任何ActiveRecord结果转换为带to_a
的数组,因此对于您的示例:
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
如果你想在v2.3之前为Rails提供一个丑陋的解决方案
JSON.parse(tasks_records.to_json) # please don't do it
答案 1 :(得分:27)
result.map(&:attributes)
如果您需要符号键:
result.map { |r| r.attributes.symbolize_keys }
答案 2 :(得分:5)
对于当前的ActiveRecord(4.2.4+),to_hash
对象上有一个方法Result
,它返回一个哈希数组。然后,您可以将其映射并转换为符号化哈希:
# 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"},
...
]