哈希组哈希值哈希值

时间:2015-07-25 21:18:49

标签: ruby-on-rails ruby activerecord hash

抱歉标题,无法表达自己更好。

我有这个:

{
  7758 => { 3259 => 10, 39625 => 10, 36410 => 20, 36238 => 20, 34951 => 20, 32101 => 10},
  7916 => { 3259 => 10, 39625 => 10, 36410 => 20, 36238 => 20, 34951 => 20, 32101 => 10},
  8857 => { 1000 => 10, 39625 => 10 }
}

这些哈希的键表示记录ID,值表示应该在其行属性中的数据。

问题是这个哈希值很重,因此对哈希表示的每个记录在数据库上发布更新是不明智的。

相反,我考虑将具有相同值的哈希分组,并且有一个结构,我可以一次性发出记录更新。

即使将嵌套的哈希值转换为json字符串,也可以比较哈希值,因为它是我们用于该列的数据类型。

最后我想为一系列具有相同哈希内容的变体发出update_all,我知道对数据库的更新问题数量是1:1到哈希值,但我有点选择在比较之前对键进行排序,我们应该有一些聪明的东西来比较现有值,而不是将内容转换为字符串以进行比较。

现在发生的是循环中每个哈希记录的正常更新:

UPDATE "table" SET "rates" = '{"3259":10,"39625":10,"36410":20,"36238":20,"34951":20,"32101":10}', WHERE "table"."variant_id" = 7758
UPDATE "table" SET "rates" = '{"3259":10,"39625":10,"36410":20,"36238":20,"34951":20,"32101":10}', WHERE "table"."variant_id" = 7916
UPDATE "table" SET "rates" = '{"1000":10,"39625":10}' WHERE "table"."variant_id" = 7916

我希望将原始结构转换为允许我执行此操作的内容:

UPDATE "table" SET "rates" = '{"3259":10,"39625":10,"36410":20,"36238":20,"34951":20,"32101":10}', WHERE "table"."variant_id" IN(7758, 7916)
UPDATE "table" SET "rates" = '{"1000":10,"39625":10}' WHERE "table"."variant_id" = 7916

我试过了

hash.group_by { |h| h[1].to_json }.each do |rate|

但我在rate

中有这个
["{\"3259\":10,\"39625\":10,\"36410\":20,\"36238\":20,\"34951\":20,\"32101\
":10}", [[7758, {3259=>10, 39625=>10, 36410=>20, 36238=>20, 34951=>20,
 32101=>10}], [7916, {3259=>10, 39625=>10, 36410=>20, 36238=>20, 
34951=>20, 32101=>10}], [8857, {3259=>10, 39625=>1...

1 个答案:

答案 0 :(得分:1)

也许是这样的:

result = hash.each_with_object({}) do |(id, attributes), result|
  json_string = attributes.to_json
  result[json_string] ||= []
  result[json_string] << id
end

result.each do |json_string, ids|
  # ...
end