to_json ActiveRecord ドキュメントは、コメントが投稿にネストされている 2 つのネストされたモデルを処理するために次のように述べています。
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"}]}
ネストされているが、深くネストされていない2 つのモデルがあるとします。ユーザーモデルとコメントモデルだとしましょう。ネストされたモデルは、ネストされた兄弟と呼ばれるものです。
json を次のようにしたいと思います。
x = {
"Blog": {
"Comments": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"User": [
{"id":2,"company":"ACME"},
{"id":4,"company":"BUD"}]
}
}
include メソッドを 2 回使用すると、ユーザーがコメントの子である一連の深くネストされた json になります。どうしたの?!
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]
)