I'm getting a bit stuck building a json object from a parent and child relationship. I have a Parent model with many Children.
I'm trying to create a JSON object as so:
{ parent_1.name: { parent_1.child.age, parent_1.child.height}, parent_1.name: { child_2.age, child_2.height}, parent_2.name: ...... }
This SO question has helped a lot but I can't figure it out completely.
I have tried this:
Parent.all.inject({}) { |hsh, p| hsh[p.name] = { p.name => p.children.inject({}) { |h,v| h[v] = {age: v.age, height: v.height}} }}
Which is really close (but horrible looking). However I only get one parent's children - I need all the parents with the children. I only need the height and age of the children. The output was like this (I have excluded the conversion to json):
{"BarryWhite"=>{:age=>"12", :height=>"45cm"}}
It should look something like this:
{"BarryWhite"=>{:age=>"12", :height=>"45cm"}, {:age => "34", :height => "108cm"}, "AndyMurray"=>{:age=>"14", :height=>"125cm"}}
How can I get this to output the correctly formatted json.