to_json ActiveRecord文档说this用于处理两个嵌套模型,其中注释嵌套在帖子中:
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]
)
答案 0 :(得分:0)
为什么你有两次blog
?
blog.to_json(
:include => { :blog => {
我认为,第二个blog
不应该在那里。试试这个:
blog.to_json(
:include => [
{
:comments => {
:except => SKIPPED_COLUMNS,
:methods => [:_type]
}
}, {
:users => {
:except => SKIPPED_COLUMNS,
:methods => [:_type]
}
}
],
:except => SKIPPED_COLUMNS,
:methods => [:_type]
)