【问题标题】:active model serializer has_many association not working活动模型序列化程序 has_many 关联不起作用
【发布时间】:2017-10-19 20:01:19
【问题描述】:

我有两个关联模型,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。

【问题讨论】:

    标签: ruby-on-rails has-many active-model-serializers


    【解决方案1】:

    我假设您使用的是 json_api 适配器。根据http://jsonapi.org/examples/ 中 JSON API 规范的示例,关联模型的“type”和“id”以外的任何其他属性都可以通过“included”属性公开。您可以查看讨论 https://github.com/rails-api/active_model_serializers/issues/1056

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多