【问题标题】:How to group Associations' attributes in a Collection (Active Model Serializer)如何在集合中对关联的属性进行分组(活动模型序列化器)
【发布时间】:2017-01-31 15:12:05
【问题描述】:

考虑以下两个实体:帖子、作者

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, author_id
  belongs_to :author
end

Class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name
end

使用 'JSON' 适配器,对于 PostsController 的索引操作,我们得到如下响应:

{
  "posts":[
    {
      "id":1,
      "title":"Hic consectetur et delectus",
      "author_id": 1,
      "author":{"id":1,"name":"Author-A"}
    },
    {
      "id":2,
      "title":"Hic consectetur et delectus",
      "author_id": 2,
      "author":{"id":2,"name":"Author-B"}
    },
    {
      "id":3,
      "title":"Hic consectetur et delectus",
      "author_id": 1,
      "author":{"id":1,"name":"Author-A"}
    }
  ]
}

是否可以将文章数据之外的作者数据分组以进行侧载? (如下图)

{
   posts:[{...}, {...}, {...}],
   authors:[
     {id:1, name:'Author-A'},
     {id:2, name:'Author-B'}
   ]
}

【问题讨论】:

  • 这很有可能,但是你会失去关系..这样做有什么意义..它与单独拥有两个 ActiveRecord 对象一样好。
  • 系统中有几个组件需要上述格式的数据。这在 AMS 0.8.x 中使用嵌入 :ids 是可能的,但在 AMS 0.10.x 中找不到等效项
  • 0.8可以认为是jsonapi的早期草稿。嵌入已包含在内。
  • @BF4 我假设您指的是关联选项中的“包含:”。否则请更正.. 这不会修改 json 格式。 (使用 json 适配器时)
  • @Pratheeswaran.R 好吧,有一个包含查询参数和一个包含的 json 根。无论如何,当我说嵌入被包含时,我并不是指代码。我的意思是 JSON:API 在达到 1.0 之前已经开发了一段时间,嵌入是包含的前身,而 AMS 是很多早期的 JSON:API 已经实现。如果我没有解决正确的问题,我深表歉意。我打算回答为什么 0.10 缺少 embed

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


【解决方案1】:

似乎您想模仿 jsonapi 包含的关系。因此,w json 适配器,post 有一个属性,为了简单起见,author_id,然后,您将 post 集合与作者分开呈现并生成响应,或者将它们混合呈现并减少它们。您也许可以只呈现为 [posts, authors]!

【讨论】:

    【解决方案2】:

    作为一种解决方法,我们创建了一个自定义适配器,扩展了 Json 适配器,并在 serializable_hash(...) 方法中将哈希修改为我们想要的格式

    class CustomAdapter < ActiveModelSerializers::Adapter::Json
      def serializable_hash(options = nil)
        result_hash = super(options)
        ... code to modify hash format ...
        result_hash
      end
    end 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      相关资源
      最近更新 更多