134

我有一个查找操作的 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 响应。我怎样才能做到这一点?

4

4 回答 4

243

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

可序列化的哈希

您还可以将任何 ActiveRecord 对象转换为 Hashserializable_hash并且您可以将任何 ActiveRecord 结果转换为 Array 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
于 2013-03-25T19:40:24.197 回答
46

或许?

result.map(&:attributes)

如果您需要符号键:

result.map { |r| r.attributes.symbolize_keys }
于 2016-07-19T07:36:06.393 回答
15

对于当前的 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"},
      ...
     ]

有关更多信息,请参阅 ActiveRecord::Result 文档

于 2016-06-20T19:33:45.203 回答
1

试试这个:-

数据=模型名称最后的

数据属性

于 2021-10-29T13:13:59.593 回答