如何组合两个序列化集合?

时间:2015-02-25 23:59:34

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

如何从两个预先序列化的集合中构建集合?换句话说,我想做这样的事情:

class ItemSerializer < ActiveModel::Serializer
  attributes :items

  has_many :things, :serializer => ThingSerializer
  has_many :other_things, :serializer => OtherThingSerializer

  def items
    things + other_things
  end

  def things
    object.things.where(:this => 'that')
  end

  def other_things
    object.other_things.where(:that => 'this')
  end
end

然而,这不起作用 - 不使用单独的序列化器..我能做到这一点的唯一方法是:

class ItemSerializer < ActiveModel::Serializer
  attributes :items

  def items
    things + other_things
  end

  def things
    object.things.where(:this => 'that').map do |thing|
      ThingSerializer.new(thing, options)
    end
  end

  def other_things
    object.other_things.where(:that => 'this').map do |other_thing|
      OtherThingSerializer.new(other_thing, options)
    end
  end
end

我真的想避免...

0 个答案:

没有答案