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

时间:2015-02-27 07:48:41

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

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

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

我的这个型号的Serializer:

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,participation_id,drink_id),所有参与(id,user_id,...)和所有饮料(id,club_id,...)。我遇到的问题是我不需要参与,我只想要DrinkPayments和各自的饮料。或者甚至更好的饮料。

是否有可能使用ActiveModel :: Serializer实现此目的?

1 个答案:

答案 0 :(得分: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