代码之家  ›  专栏  ›  技术社区  ›  Gabriel O

活动模型序列化程序有许多关联无法工作

  •  2
  • Gabriel O  · 技术社区  · 8 年前

    我有两个相关模型 parent= Activity 它与成本有许多关联。

    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 
    

    输出有点不同,没有关系,但有我想要的序列化程序属性。 我正在使用Rails 5.1.3和AMS 0.10。

    1 回复  |  直到 8 年前
        1
  •  1
  •   jsonb.uy    7 年前

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