Converting Active Record to a hash array

I saw this...

How to convert activerecord results to a hash array

and I wanted to create a method that would allow me to turn any copied or uncoordinated record 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?

+4
source share
2 answers

You probably need to call all too. It’s just that to_a will work fine in a scope or an 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 all.to_a is a little duplicate, since all already returns an array, but in Rails 4 it will be necessary.

+14
source

You are doing an action on a class, not an instance of a class. You can either cancel self. , then call this on the instance, or call it on the collection that you need to pass to the class method:

 def self.to_hash(collection) collection.to_a.map(&:serializable_hash) end 
+1
source

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


All Articles