【问题标题】:Only serialize a single object with ActiveModel::Serializer仅使用 ActiveModel::Serializer 序列化单个对象
【发布时间】:2015-02-27 07:48:41
【问题描述】:

在我的项目中,我有一个模型 DrinkPayment:

class DrinkPayment < ActiveRecord::Base
  #Association
  belongs_to :drink
  belongs_to :participation
end

还有我的这个模型的序列化器:

class DrinkPaymentSerializer < ActiveModel::Serializer
  ActiveModel::Serializer.setup do |config|
    config.embed = :ids
    config.embed_in_root = true
  end

  attributes :id, :participation_id, :drink_id

  has_one :participation
  has_one :drink
end

这样做会给我所有的 DrinkPayments(id、partition_id、drink_id)、所有的 Participations(id、user_id、...)和所有的 Drinks(id、club_id、...)。我遇到的问题是我不需要参与,我只需要 DrinkPayments 和相应的饮料。或者更好的只是饮料。

是否有可能使用 ActiveModel::Serializer 实现这一点?

【问题讨论】:

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


    【解决方案1】:

    只需更改 DrinkPaymentSerializer 以反映您的需要:

    class DrinkPaymentSerializer < ActiveModel::Serializer
      attributes :id
    
      has_one :drink
    end
    

    你可以在序列化器中添加任何你想要的东西:

    class DrinkPaymentSerializer < ActiveModel::Serializer
      attributes :drink_name, :price
    
      def drink_name
        object.drink.name
      end
    
      def price
        { amount: object.amount, currency: object.currency }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 2014-10-17
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      相关资源
      最近更新 更多