Turn an array of Active Record objects into a hash

I have an array of Active Record objects. I would like to create a hash that serves as an index. My Active Record objects have nameand properties value.

Ideally, I would like to iterate over the array and create a hash that will create something similar to:

hash[name] = value

What is the best way to create an array footo create a hash similar to the one above?

+4
source share
2 answers

Something like this will work:

hash = {}
Model.all.map { |i| hash[i.id] = i }

hash must then evaluate:

{
  :1 => #<ActiveRecord:1>,
  :2 => #<ActiveRecord:2>,
  ...
}
+2
source

You can use the method Hash::[].

relation = Record.where("query")

Hash[
  relation.to_a.map do |obj|
    [obj.name, obj.value]
  end
]
0
source

Source: https://habr.com/ru/post/1613892/


All Articles