Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Active Record set into an array of hashes

I saw this...

How to convert activerecord results into a array of hashes

and wanted to create a method that would allow me to turn any scoped or non-scoped record set into an array of hashes. I added this to my model:

 def self.to_hash
   to_a.map(&:serializable_hash)
 end

However, I get this error.

NameError: undefined local variable or method `to_a' for #<Class:0x007fb0da2f2708>

Any idea?

like image 500
user2012677 Avatar asked Dec 05 '22 10:12

user2012677


2 Answers

You probably need to call all on that too. Just the to_a would work fine on a scope or existing result set (e.g. User.active.to_hash) but not directly on the model (e.g. User.to_hash). Using all.to_a will work for both scenarios.

def self.to_hash
  all.to_a.map(&:serializable_hash)
end

Note that the all.to_a is a little duplicative since all already returns an array, but in Rails 4 it will be necessary.

like image 50
Dylan Markow Avatar answered Dec 18 '22 10:12

Dylan Markow


You're performing the action on a class, not an instance of the class. You can either take away the self. then call this on an instance, or to call it on a collection you need to pass the collection into the class method:

def self.to_hash(collection)
  collection.to_a.map(&:serializable_hash)
end
like image 28
Matt Avatar answered Dec 18 '22 11:12

Matt