to_json ActiveRecord 文档说这用于处理两个嵌套模型,其中评论嵌套在帖子中:
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"}]}
假设我有两个嵌套但没有深度嵌套的模型。可以说它是一个用户模型和评论模型。嵌套模型就是我所说的嵌套兄弟。
我希望我的 json 看起来像这样:
x = {
"Blog": {
"Comments": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"User": [
{"id":2,"company":"ACME"},
{"id":4,"company":"BUD"}]
}
}
当我两次使用 include 方法时,我最终得到的是一系列深度嵌套的 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]
)