R
R
Ruslan Galiev2014-08-25 14:04:21
Ruby on Rails
Ruslan Galiev, 2014-08-25 14:04:21

Ruby on Rails how to convert ActiveRecord:Relation selection to hash?

Hello
Tell me how to convert such a selection to a hash where the key will be the external_key field, which is 100% unique.
Sample:

Customer.all
[#<Customer id: 1, name: "Рога", external_key: "00002256">,  #<Customer id: 1, name: "Копыта", external_key: "00002257">]

The hash you wanted to get?
{'00002256' => 1, '00002257' => 2}
I want to get a hash of such a plan in order to make it easier to search by the external_key field.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Platonov, 2014-08-25
@HerMajor

hash = {}
Customer.all.find_each { |c| hash[c.external_key] = c.id }

V
vsuhachev, 2014-08-26
@vsuhachev

Customer.all.pluck(:external_key, :id).to_h

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question