仅使用ActiveModel::Serializer序列化单个对象



在我的项目中,我有一个模型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,…)和所有的drink(id,club_id,…)。我的问题是我不需要Participationss,我只想要DrinkPayment和相应的饮料。或者只喝饮料更好。

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

只需更改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

最新更新