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:
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.
One note about this: this can hit n+1 queries pretty hard. Unless you put include: in your associations (which I wouldn’t not recommend unless it makes sense, and it probably doesn’t) you have to know at query time what to include (or use joins), and what I just posted would make that difficult.
If you do use ActiveModel::Serializers instead and have big serialized objects, look at yodo to help you identify the value for include: in your queries to avoid n+1:
#### hashify specified model association
sub_collection_names.each do |name|
if(obj.class.reflections.keys.include?(name))
tmp_hash[name] =
ActiveSupport::JSON.decode(obj.send(name).to_json)
end
end
hashed_collection << tmp_hash
end
return hashed_collection
end
[/code]