user2012677
user2012677

Reputation: 5735

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?

Upvotes: 4

Views: 13549

Answers (2)

Matt
Matt

Reputation: 14038

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

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124419

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.

Upvotes: 14

Related Questions