如何ActiveRecord的结果转换成散列的数组(How to convert ActiveRec

2019-07-21 16:49发布

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

Answer 1:

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

您也可以将任何ActiveRecord对象的哈希与serializable_hash ,你可以在任何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


Answer 2:

也许?

result.map(&:attributes)

如果你需要的符号键:

result.map { |r| r.attributes.symbolize_keys }


Answer 3:

对于当前的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 ::结果文档的更多信息 。



文章来源: How to convert ActiveRecord results into an array of hashes