简体   繁体   English

有没有办法使用 ActiveModel Serializer 序列化父级之外的嵌套属性?

[英]Is there a way to serialize nested attributes outside of the parent with ActiveModel Serializer?

I upgraded activemodel serializer and now the output is different than what it once was.我升级了 activemodel 序列化程序,现在输出与以前不同。 I'm trying to get the JSON output to match what it previously was.我试图让 JSON 输出与以前的输出相匹配。 Specifically, I'd like an objects nested attributes to be on the same level as the main object.具体来说,我希望对象嵌套属性与主对象处于同一级别。

For example, let's say my serializer is as follows:例如,假设我的序列化程序如下:

class DishesSerializer < ActiveModel::Serializer
  has_many :ingredients
end

This would be the current output:这将是当前的输出:

{
  "dish": {
      "dish_stuff_1": "dish_stuff_1",
      "dish_stuff_2": "dish_stuff_2",
      "dish_stuff_3": "dish_stuff_3",
      "ingredients": {
          "ingredients_stuff_1": "ingredients_stuff_1"
      }
  }
}

And what I'd like is something like this:我想要的是这样的:

{
  "dish": {
      "dish_stuff_1": "dish_stuff_1",
      "dish_stuff_2": "dish_stuff_2",
      "dish_stuff_3": "dish_stuff_3"
  }
  "ingredients": {
      "ingredients_stuff_1": "ingredients_stuff_1"
  }
}

I am currently doing this in the controller using multiple serializers, but it takes some additional querying and feels wrong.我目前正在使用多个序列化程序在控制器中执行此操作,但它需要一些额外的查询并且感觉不对。 I feel like there should be some hacky way to do it in AMS.我觉得在 AMS 中应该有一些 hacky 的方法。 I tried something like this:我试过这样的事情:

  def attributes
    hash = super
    hash.merge!(:dishes => dishes)
  end

but that ends up in the same layer.但最终在同一层。

Any help would be greatly appreciated.任何帮助将不胜感激。

In this case, can't you just create a new serializer that has all the data you need - say a menu serializer:在这种情况下,您不能创建一个新的序列化程序来包含您需要的所有数据——比如说菜单序列化程序:

class MenuSerializer < ActiveModel::Serializer
 
  has_one :dish
  has_many :ingredients

end

Not sure having a serializer that returns 2 root elements is a good idea, as that would make it hard to reuse in the future.不确定有一个返回 2 个根元素的序列化程序是个好主意,因为这会使将来难以重用。

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

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