Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRelation to hash

I need to hashify ActiveRelation! For example I have such AR

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

Is here a way simple to create hash with primary keys of MyTable as keys in 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"}}
like image 812
Fivell Avatar asked Dec 05 '22 18:12

Fivell


1 Answers

Try index_by:

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

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

like image 80
klochner Avatar answered Dec 15 '22 00:12

klochner