【问题标题】:Rails define custom json structureRails 定义自定义 json 结构
【发布时间】:2020-01-04 01:19:24
【问题描述】:

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

    简单的 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
    

    【讨论】:

    • 诚然,我从来都不是 JBuilder 的粉丝(DHH 可能是唯一的 JBuilder 粉丝,这只是因为他构建了它)。用这种奇怪的笨拙(而且很慢)的模板 DSL 来构建散列和数组就是这么倒退。至少 AMS 有面向对象的工作。
    • 哦,是的,很慢。在我运行的每份分析器报告中都很亮眼:)
    • 很想坚持使用纯红宝石 - 这看起来很有希望,谢谢。您的意思是notes.each_with_object 而不是上面的users.each_with_object
    • 我不断收到undefined method id' for {:notes=>{}}:Hash 我错过了什么吗?
    • 对不起,我的错误应该是 notes 而不是 users 和切换的参数。我似乎永远记不起each_with_object 的参数顺序。
    猜你喜欢
    • 2020-04-15
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多