【问题标题】:Rails Active Model Json serializer: returning has_many record as has_oneRails Active Model Json 序列化程序:将 has_many 记录返回为 has_one
【发布时间】:2017-12-05 11:24:58
【问题描述】:

我有一个模型的活动模型 JSON 序列化器,它有一个 has_many 关系,我想包含在 JSON 响应中。

我希望将记录包含为 has_one 而不是 has_many 记录 - 仅包含第一条记录:

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_many :body_parts
end

在这里,body_parts 应返回为 has one :body_part。最好的方法是什么?

【问题讨论】:

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


    【解决方案1】:

    如果您只想返回第一个 body_part 并且只在您的序列化程序响应中执行此操作,那么最好将其定义为 PersonSerializer 中的方法。

    class PersonSerializer < ActiveModel::Serializer
      attributes :name, :symbol
      has_one :body_part, serializer: BodyPartSerializer
      ...
      def body_part
        self.object.body_parts.first
      end
    end
    

    假设您有一个单独的用于 BodyPart 模型的序列化程序。

    【讨论】:

      【解决方案2】:

      是不是很简单:

      class Person
        def body_part
          body_parts.first
        end
      
        # or
      
        has_one :body_part, -> { order(id: :asc) }
      end
      
      class PersonSerializer < ActiveModel::Serializer
        attributes :name, :symbol
        has_many :stats
        has_one :body_part
      end
      

      在这两种情况下,您都需要具体说明成为 first 身体部分的确切含义。

      【讨论】:

        猜你喜欢
        • 2014-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 2016-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多