Rob
Rob

Reputation: 1855

Pluck doesn't return a bother records they have the same name

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.

Upvotes: 0

Views: 255

Answers (1)

Francis.TM
Francis.TM

Reputation: 1801

I'm not sure why you need convert pluck result into a Hash, because it was an Array original.

Like you have three CategoryItemValue like below:

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

when you pluck them directly, you will get a array like:
[ ['foo', 'bar1'], ['foo', 'bar2'], ['baz', 'bar3'] ]

but when you convert it into a hash, you will get:
{'foo' => 'bar2', 'baz' => 'bar3' }

because new hash value will override the old one if key ( foo in the example above) exists.

Or you could try Enumerable#group_by method:
CategoryItemValue.where(...).pluck(:key, :value).group_by { |arr| arr[0] }

Upvotes: 1

Related Questions