Link to home
Create AccountLog in
Avatar of clemcrock
clemcrock

asked on

Creating nested hash from nested active record results

Hello,
  I'm trying to find a very abstract and "one size fits all" for converting nested active record results to nested hashes.   It's easy, to do one level deep as such:
 
results_to_hash = Hash[ found_categories.map{ |c| [c.id, c.title]}]

Open in new window


But, when I try to add another collection to the mix, it completely borks and the results_to_hash only returns an empty hash IE:

results_to_hash = Hash[ found_categories.map{ |c| [c.id, c.title, c.categories]}]

Open in new window


Ultimately, I'd like it to be smart enough to detect if a model object contains a collection (IE: object.class.reflect_on_all_associations), and automatically convert those to hashes.


Any ideas?

Thanks,
Eric
Avatar of F. Dominicus
F. Dominicus
Flag of Germany image

It might be that you need a deep copy of the collection. AFAIK are assignments to array just "shallow" that means if you have a collection [1,2,3]

and you add it to a hash
ht.Add(key => #someKey, value => #collection)
and you change a collection thereafter the  hash table collection gets influenced also.

So in this case you probably want to use clone

If not please provide code that we can use.

Regards
ASKER CERTIFIED SOLUTION
Avatar of clemcrock
clemcrock

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer