将ActiveModel :: Serializer从v0.9.2迁移到0.8,has_many未被序列化

时间:2015-03-19 02:37:25

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

我有以下ActiveModel::Serializer

class MyThingySerializer < ActiveModel::Serializer
  root false

  attributes :id, :name, :description

  has_many :whatsits, embed_namespace: :_embedded

  delegate :whatsits, to: :object

end

在AMS 0.9.2下工作正常但是,为了使用include_attributename?机制添加可选属性,我被告知回滚到AMS 0.8

现在我的whatsits没有显示在_embedded属性下的序列化输出中。

我需要做些什么特别的事情才能让我的嵌入式whatsits回来?

更新

我尝试将以下方法添加到我的序列化程序中:

def whatsits
  associated = self.class._associations[:whatsits]
  associated.options[:root] = associated.options[:embed_namespace]
  associated.options[:embed] = :objects
  associated.options[:include] = true
  object.whatsits
end

希望序列化程序能够在whatsits键下发出_embedded列表,但是唉还没有工作..

1 个答案:

答案 0 :(得分:0)

这很有效。

class MyThingySerializer < ActiveModel::Serializer
  root false

  attributes :id, :name, :description, :_embedded

  # force the whatsits list to sit under '_embedded'.
  def _embedded
    {
      whatsits: object. whatsits.map {|whatsit| WhatsitSerializer.new(whatsit) } || []
    }
  end
end