Rails ActiveRelation for Hash

I need hashify ActiveRelation! For example, I have such an AR

arel = MyClass.page(options[:page]).per(options[:per]) 

It’s easy here to create a hash with MyTable primary keys as keys in the hash

Ex1:

 [#<Object id: 44, name: "name44" >, #<Object id: 2, name: "name2" >, #<Object id: 110, name: "name110">] => {44=>"name44", 2=>"name2",110=>"name110"} 

Ex2:

 [#<Object id: 44, name: "name44" >, #<Object id: 2, name: "name2" >, #<Object id: 110, name: "name110">] => {44=>{:id=>44, :name=>"name44", 2=>{:id=>2,:name=>"name2"},110=>{:id=>110,:name=>"name110"}} 
+4
source share
3 answers

Try index_by :

 MyClass.limit(20).all.index_by(&:id) 

http://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by

+12
source

You can do it manually, there is no function in the Array class.

 hsh = {} objects.each { |u| hsh.merge!({ u.id => { :name => u.name } }) 
+2
source

Try serializable_hash , here .

+1
source

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


All Articles