【问题标题】:How to avoid nesting in Serializer on has_one association?如何避免在 has_one 关联上的 Serializer 中嵌套?
【发布时间】:2015-02-06 05:22:34
【问题描述】:

我有 ProfileSerializer:

class ProfileSerializer < ActiveModel::Serializer
  attributes :id, :role, :name
  has_one :company
end

我明白了

{"user": {"id":7,"role":"guest","name":"misa","company":{"id":2,"user_id":7, ...}}

我有机会避免“公司”嵌套并获得这样的 JSON:

{"user": {"user_info": {"id":7,"role":"guest","name":"misa"}, "company_info": {"id":2,"user_id":7, ...}}}

【问题讨论】:

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


    【解决方案1】:

    你可以试试这个:

    class ProfileSerializer < ActiveModel::Serializer
      attributes :id, :role, :name, :company_info
    
      def company_info
        object.company
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      相关资源
      最近更新 更多