从数据库记录添加一个新的字段到每个现有的哈希散列更新的数组 [英] Update an array of hashes with records from the database adding a new field into each existing hash

查看:98
本文介绍了从数据库记录添加一个新的字段到每个现有的哈希散列更新的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为记录与哈希千阵列(见第一阵列,​​显示如下)。目前,每个哈希包含两个字段 ID PARENT_ID 。我想补充的updated_at 一个新字段存储在数据库中(请参阅下面的第二个阵列)。

I have an array called records with thousand of hashes (see the first array showed below). Every hash contains currently two fields id and parent_id. I want to add a new field called updated_at which is stored in the database (see the second array below).

records = [{"id"=>3, "parent_id"=>2}, 
           {"id"=>4, "parent_id"=>2}]

records = [{"id"=>3, "parent_id"=>2, "updated_at"=>"2014-03-21 20:44:35 UTC"}, 
           {"id"=>4, "parent_id"=>2, "updated_at"=>"2014-03-21 20:44:34 UTC"}] 

我的第一种方法是以下步骤之一,但它执行查询的数据库,每一个哈希,所以如果我有1K哈希数组中,它要执行1K疑问,我认为这是不是从很好性能上来看。

My first approach is the following one, but it executes a query to the database for every hash, so if I have 1K hashes in the array, it is going to execute 1K queries, which I think is not very good from the performance point of view.

records.each do |record|
  record['updated_at'] = Record.find(record['id']).updated_at.utc.to_s
end

您能否提供我一个更好的解决方案?

Can you suggest me a better solution?

推荐答案

怎么这样呢?散了查询,通过聚合的IDS片的时间。调整 each_sli​​ce 量的东西,表现良好......

How about something like this? Bulk up the queries by aggregating the ids a slice at a time. Adjust each_slice amount to something that performs well...

records.each_slice(250) do |records|
  ids = records.map { |r| r['id'] }
  results = Record.select([:id, :updated_at]).find(ids)
  records.each do |rec|
    result = results.find { |res| res.id == rec.id }
    rec['updated_at'] = result.updated_at.utc.to_s
  end
end

这篇关于从数据库记录添加一个新的字段到每个现有的哈希散列更新的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆