繁体   English   中英

Rails 定义自定义 json 结构

[英]Rails define custom json structure

我正在尝试构建一个 json 响应来模仿我们在应用程序中其他地方的现有结构(使用 jbuilder 模板)。 在这个特定用例中,我们无法使用 jbuilder 模板,因为我们正在为从模型方法触发的实时更新作业准备 json 数据,而不是响应控制器中的服务器调用。

所需结构:

{"notes": {
  "1": {
    "id": "1", 
    "name": "Jane", 
    ... 
  },
  "2": {
    "id": "2",
    "name": "Joe", 
    ... 
  }
 }
}

Jbuilder模板(供参考):

json.notes do
  for note in notes 
    json.set! note.id.to_s do
      json.id note.id.to_s
      json.name note.name
      ...
    end
  end
end

我已经尝试在模型类(如下)中定义一个 to_builder 方法,根据 jbuilder 文档和活动模型序列化程序,但似乎无法将哈希嵌套在 id 属性下。 任何方向将不胜感激!

to_builder 方法

def to_builder
  Jbuilder.new do |note|
    note.set! self.id do
      note.(self, :id, :name, ...)
    end
  end
end

只是普通的 Ruby 怎么样?

notes.each_with_object({"notes": {}}) do |note, hash|
  hash["notes"][note.id.to_s] = note.as_json
end

或 AMS:

adapter = ActiveModelSerializers::Adapter
notes.each_with_object({"notes": {}}) do |note, hash|
  hash["notes"][note.id.to_s] = adapter.create(NoteSerializer.new(note))
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM