Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON include syntax

My setup: Rails 2.3.10, Ruby 1.8.7

I have a rather complicated set of relationships between several models.

class A
  has_many :classB
  has_many :classD
end

class B
  belongs_to :classA
  has_many :classC
end

class C
  belongs_to :classB
  belongs_to :classE
end

class D
  belongs_to :classA
  belongs_to :classE
end

class E
  has_many :classD
  has_many :classC
end

I'm having an issue with the JSON syntax to get all the related information starting with classA. Here's what I have working so far.

classA.to_json(:include => {:classB => {:include => [:classC, :classE]}})

I can't get the syntax working to also include classD and related classE records.

UPDATE Actually something like this might work except that I can't mix hashes and arrays

classA.to_json(:include => [ :classB => { :include => { :classC => { :include => :classE } } },
                             :classD, :classE  ])

Note that I didn't use singular/plural in my example code above but in my real code, I am. Any insights will be much appreciated.

Thanks, Bob

like image 557
Bob Avatar asked Jan 11 '11 03:01

Bob


1 Answers

This should work:

classA.to_json(:include => {
  :classB => {:include => {:classC => {:include => :classE}}},
  :classD => {},
  :classE => {},
})
like image 68
tokland Avatar answered Sep 30 '22 05:09

tokland