【问题标题】:Is there a way to serialize nested attributes outside of the parent with ActiveModel Serializer?有没有办法使用 ActiveModel Serializer 序列化父级之外的嵌套属性?
【发布时间】:2021-09-21 23:57:00
【问题描述】:

我升级了 activemodel 序列化程序,现在输出与以前不同了。我试图让 JSON 输出与以前的输出相匹配。具体来说,我希望对象的嵌套属性与主对象处于同一级别。

例如,假设我的序列化器如下:

class DishesSerializer < ActiveModel::Serializer
  has_many :ingredients
end

这将是当前的输出:

{
  "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"
      }
  }
}

而我想要的是这样的:

{
  "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"
  }
}

我目前正在使用多个序列化程序的控制器中执行此操作,但它需要一些额外的查询并且感觉不对。我觉得在 AMS 中应该有一些 hacky 方法来做到这一点。 我试过这样的事情:

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

但最终在同一层。

任何帮助将不胜感激。

【问题讨论】:

    标签: ruby ruby-on-rails-4 active-model-serializers


    【解决方案1】:

    在这种情况下,您不能只创建一个包含您需要的所有数据的新序列化程序吗?比如菜单序列化程序:

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

    不确定有一个返回 2 个根元素的序列化程序是一个好主意,因为这会使其难以在未来重用。

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2015-04-25
      • 1970-01-01
      • 2020-12-20
      • 2011-04-18
      相关资源
      最近更新 更多