Rails定义自定义json结构

问题描述 投票:0回答:1

我正在尝试构造一个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

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

to_builder方法

def to_builder
  Jbuilder.new do |note|
    note.set! self.id do
      note.(self, :id, :name, ...)
    end
  end
end
ruby-on-rails json jbuilder
1个回答
0
投票

只是普通的Ruby怎么样?

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

或AMS:

adapter = ActiveModelSerializers::Adapter
users.each_with_object({"notes": {}}) do |hash, note|
  hash["notes"][note.id.to_s] = adapter.create(NoteSerializer.new(note))
end
© www.soinside.com 2019 - 2024. All rights reserved.