The to_json ActiveRecord docs say this for dealing with two nested models, where comments is nested in posts:
konata.to_json(:include => { :posts => {
:include => { :comments => {
:only => :body } },
:only => :title } })
# => {"id": 1, "name": "Konata Izumi", "age": 16,
"created_at": "2006/08/01", "awesome": true,
"posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
"title": "Welcome to the weblog"},
{"comments": [{"body": "Don't think too hard"}],
"title": "So I was thinking"}]}
Suppose I have two models that are nested, but not deeply nested. Lets say its a user model and comments model. The nested Models would be what I call nested siblings.
I would like my json to look like this:
x = {
"Blog": {
"Comments": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"User": [
{"id":2,"company":"ACME"},
{"id":4,"company":"BUD"}]
}
}
When I use the include method twice, what I end up is a series of deeply nested json, where users are children of comments. whats wrong?!
data.to_json(
:include => { :blog => {
:include => [{ :comments => {
:except => SKIPPED_COLUMNS,
:methods => [:_type]
}},
{ :users => {
:except => SKIPPED_COLUMNS,
:methods => [:_type]
}}],
:except => SKIPPED_COLUMNS,
:methods => [:_type]
}},
:except => SKIPPED_COLUMNS,
:methods => [:_type]
)