0

I have a pluck that is turned into a hash and stored in a variable

@keys_values_hash = Hash[CategoryItemValue.where(category_item_id: @category_item.id).pluck(:key, :value)]

If 2 records have the same :key name then only the most recent record is used and they aren't both added to the hash. But if they have the same value and different keys both are added to the hash.

This also occurs if I swap :key and :value around (.pluck(:value, :key)). If they have now the same value it only uses the most recent one and stores that in the hash. But having the same key is now fine.

I'm not sure of this is being caused by pluck or from being sorted in a hash. I'm leaning towards pluck being the culprit.

What is causing this and how can I stop it from happening. I don't want data being skipped if it has the same key name as another record.

4

1 回答 1

1

我不确定为什么需要将 pluck 结果转换为 Hash,因为它是 Array 原始文件。

就像你有CategoryItemValue以下三个:

id,   key,   value
 1,    foo,   bar1
 2,    foo,   bar2
 3,    baz,   bar3

当你直接采摘它们时,你会得到一个像这样的数组:
[ ['foo', 'bar1'], ['foo', 'bar2'], ['baz', 'bar3'] ]

但是当你把它转换成哈希时,你会得到:
{'foo' => 'bar2', 'baz' => 'bar3' }

foo因为如果键(在上面的示例中)存在,新的哈希值将覆盖旧的哈希值。

或者你可以试试Enumerable#group_by方法:
CategoryItemValue.where(...).pluck(:key, :value).group_by { |arr| arr[0] }

于 2016-02-17T04:25:03.163 回答