【问题标题】:How to convert ActiveRecord results into an array of hashes如何将 ActiveRecord 结果转换为哈希数组
【发布时间】:2023-03-05 08:33:01
【问题描述】:

我有一个查找操作的 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 响应。我该怎么做?

【问题讨论】:

标签: arrays activerecord hash


【解决方案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

您还可以使用 serializable_hash 将任何 ActiveRecord 对象转换为哈希,并且您可以使用 to_a 将任何 ActiveRecord 结果转换为数组,例如:

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 建议 serializable_hash - 这是我第一次遇到提到这一点的答案。遗憾的是,我目前正在使用最后一个 JSON 解决方案,但现在将考虑使用 serializable_hash。我只需要找出如何在每条记录中包含类名,就像在 JSON 中包含 root 一样。
  • @Dom웃 如果我理解正确,请参阅:stackoverflow.com/questions/17090891/…
  • @Dom 在下面看到我的回答。
  • 另一种可能的方式是tasks_records = TaskStoreStatus.all.map(&amp;:attributes)
  • 这里真的很棒的解决方案,但我的问题可能是 使用 .as_json&amp;:serializable_hash&amp;:attributes 有什么好处?它与 ActiveRecord 助手有关还是直接与性能有关? 在此先感谢各位! @Dom @Rigo @Fredrik E
【解决方案2】:

可能吗?

result.map(&:attributes)

如果你需要符号键:

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

【讨论】:

    【解决方案3】:

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

    See the ActiveRecord::Result docs for more info.

    【讨论】:

    • 不能比这更简单明了。非常感谢。
    • 如果您的 ActiveRecord 版本无法识别 to_hash 方法,请注意:请改用 to_ary。奇怪的是,这对我有用。
    【解决方案4】:

    试试这个:-

    数据 = 型号名称最后

    data.attributes

    【讨论】:

      猜你喜欢
      • 2015-02-14
      • 2015-11-26
      • 2019-10-27
      • 2019-05-23
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      相关资源
      最近更新 更多