gpt4 book ai didi

ruby-on-rails - 事件模型序列化程序,没有数组根,但有子根

转载 作者:行者123 更新时间:2023-12-04 03:38:08 25 4
gpt4 key购买 nike

我已将事件模型序列化程序 gem 添加到一个项目中,但它破坏了一堆东西,我们的一个 api 具有我需要保留的非常特定的格式,不幸的是,我似乎无法获得遗留行为。

#Models
class Parent < ActiveRecord::Base
attr_accessable, :id, :name, :options
has_many :children
end

class Child < ActiveRecord::Base
attr_accessable, :id, :name
end

#Controller
class ParentsController < ApplicationController

respond_to :json

def index
#Was
@parents = Parent.all
respond_with @parents, :include => [:children]

#Is (and is not working)
@parents = Parent.includes(:children)
respond_with @parents, each_serializer: ::ParentsSerializer, root: false #Not working
end
...
end

#Serializer
class ParentSerializer < ActiveModel::Serializer
attrs = Parent.column_names.map(&:to_sym) - [:options]
attributes(*attrs)
has_many :children

def filter(keys)
keys.delete :children unless object.association(:children).loaded?
keys.add :options
keys
end
end

期望输出
[
  {
    "parent": {
      "id": 1,
      "name": "Uncle",
"options":"Childless, LotsOfLoot",
      "children": []
    }
  },
  {
    "parent": {
      "id": 2,
      "name": "Mom",
"options":"<3 Gossip, SoccerMom",
      "children": [
        {
          "child": {
            "id": 10,
            "name": "susy"
          }
        },
        {
          "child": {
            "id": 11,
            "name": "bobby"
          }
        }
      ]
    }
  }
]

我需要的是将 json 格式化为不包含顶级根但包含子根的格式...我知道我可以使用 Rabl 之类的东西,但是如果有一种简单的方法用 ActiveModel Serializers 做到这一点,那会更好。

最佳答案

令我惊讶的是,似乎没有直接支持这一点,我迷失了想知道你会覆盖什么来添加它。但是解决方法也不错 - 只需定义一个自定义 children方法:

#Serializer
class ParentSerializer < ActiveModel::Serializer
attrs = Parent.column_names.map(&:to_sym) - [:options]
attributes(*attrs)
has_many :children

def filter(keys)
keys.delete :children unless object.association(:children).loaded?
keys.add :options
keys
end

def children
object.children.collect{|c| ChildSerializer.new(c, scope).as_json(root: :child)}
end
end

你正在做 ArraySerializer 的工作在 children方法,但我不确定没有 AM::S 支持的更干净的方法。

关于ruby-on-rails - 事件模型序列化程序,没有数组根,但有子根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com