views:

59

answers:

0

Hi - I have a model like this

class Parent < ActiveRecord::Base
  :has_many :kids
end

class Kid < ActiveRecord::Base
  :has_many :grandkids
  :belongs_to :parent
end

I can generate json like this:

the_parent.to_json( :methods => [:kids] )

=> { "parent" : { "kids" : [ { "kid" : { "name" => "kid0" .... and so on. Just what I want. Each object looks like a hash with a single key - which is the model name - and the value is an attribute hash. Great.

But I get into trouble when I try to serialize the whole tree, like this:

the_parent.to_json( :include => { :kids => { :include => :grandkids } } )

=> { "parent" : { "kids" : [ { "name" => "kid0" ... which is missing the model names in the "kids" array. The same thing happens at the next level with the grandkids. I'm going to parse this somewhere else, and it would help to have certainty about the object name (as opposed to relying on convention using the relationship name). The docs advertise this:

ActiveRecord::Base.include_root_in_json = true

Which I found it to have no effect. My guess is the different behavior has something to do with the difference between the :method and :include options, but I can't wrangle the :method syntax to get the nesting I need, and I'm not sure if that will work even if it compiles.

Any ideas? Thanks, Dan