【问题标题】:RABL: JSON objects without root keyRABL:没有根键的 JSON 对象
【发布时间】:2026-01-21 16:00:02
【问题描述】:

我有这个 rabl 模板:

object @photo
attributes :id
child :comments do
  attributes :id, :body
end

这给了我这个 JSON 响应:

{
  photo: {
    id: 1,
    comments: [
      { 
        comment: {
          id: 1,
          body: 'some comment'
        }
      },
      { 
        comment: {
          id: 2,
          body: 'another comment'
        }
      }
    ]
  }
}

但我希望它看起来像这样:

{
  id: 1,
  comments: [
    { 
      id: 1,
      body: 'some comment'
    },
    { 
      id: 2,
      body: 'another comment'
    }
  ]
}

为什么 rabl 用一个名为 comment 的额外对象包装数组中的每个元素。这样,当我在 javascript 中访问集合时,我必须编写:

var comment = image.comments[0].comment

代替:

var comment = image.comments[0]

我知道,如果我在 @photo 对象的属性列表中包含 :comments,它会按照我想要的方式工作,但是当我想要每个 comment 对象的另一个级别的嵌套关联时,没有除了使用child 之外的处理方法,但这给了我不想要的 JSON 响应。

也许我只是误解了整个事情——有人可以解释或帮助吗?谢谢!

【问题讨论】:

    标签: ruby-on-rails json rabl


    【解决方案1】:

    知道了!

    config/initializers/rabl_config.rb中新建一个文件:

    Rabl.configure do |config|
      config.include_json_root = false
      config.include_child_root = false
    
    end
    

    【讨论】:

    • 我遇到了同样的问题,发现除了include_json_root = false之外还需要添加“config.include_child_root = false”
    最近更新 更多