簡體   English   中英

活動模型序列化程序 has_many 關聯不起作用

[英]active model serializer has_many association not working

我有兩個關聯模型, parent= Activity ,它與 Cost 有_many 關聯。 我做了一個 API 調用來獲取使用序列化程序的活動詳細信息,並且還想添加 Cost 序列化。 所以在 ActivitySerializer 里面我試過這個:

Class ActivitySerializer: < ActiveModel::Serializer


ActiveModel::Serializer.config.key_transform = :unaltered




attributes :id, 
          :name, 
          :description
 ...
has_many costs, each_serializer: CostSerializer
end

CostSerializer 看起來像這樣:

class CostSerializer < ActiveModel::Serializer

ActiveModel::Serializer.config.key_transform = :unaltered

attributes  :id, 
          :amount, 
          :description
end

結果是活動數據看起來不錯,但成本數據給了我這個:

relationships":{"costs":{"data":[{"id":"20","type":"costs"}]}

不知道為什么金額和描述會下降。 如果我這樣做,它會起作用(將 listCosts 添加到 ActivitySerializer 中的屬性):

def listCosts
  object.costs.map do |cost|
    CostSerializer.new(cost, scope:scope, root: false, event: object)
  end
end 

輸出有點不同,沒有關系,但確實有我想要的序列化器屬性。 我正在使用帶有 AMS 0.10 的 Rails 5.1.3。

我假設您正在使用 json_api 適配器。 根據http://jsonapi.org/examples/ 中JSON API 規范的示例,除了關聯模型的“type”和“id”之外的任何其他屬性都可以通過“included”屬性公開。 您可以查看https://github.com/rails-api/active_model_serializers/issues/1056 中的討論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM