active_model_serializers/lib/active_model/array_serializer.rb
Arne Brasseur 1db96ec7a9 When using embed: :ids ; embed_in_root: true, and serializing multiple objects,
only the associated objects of the last object in the collection will actually
show up in the serialized data.

For example, if you serialize a collection of two posts, each containing one or
more comments, only the comments of the last post show up. The reason is a
Hash#merge wich overwrites the array rather than appending to it.

This commit fixes this by merging the collection arrays, rather than the top-level
hashes.
2013-11-11 14:30:34 +01:00

55 lines
1.4 KiB
Ruby

require 'active_model/default_serializer'
require 'active_model/serializable'
require 'active_model/serializer'
module ActiveModel
class ArraySerializer
include Serializable
class << self
attr_accessor :_root
alias root _root=
alias root= _root=
end
def initialize(object, options={})
@object = object
@root = options.fetch(:root, self.class._root)
@meta_key = options[:meta_key] || :meta
@meta = options[@meta_key]
@each_serializer = options[:each_serializer]
@options = options.merge(root: nil)
end
attr_accessor :object, :root, :meta_key, :meta
def json_key
if root.nil?
@options[:resource_name]
else
root
end
end
def serializer_for(item)
serializer_class = @each_serializer || Serializer.serializer_for(item) || DefaultSerializer
serializer_class.new(item, @options)
end
def serializable_array
@object.map do |item|
serializer_for(item).serializable_object
end
end
alias_method :serializable_object, :serializable_array
def embedded_in_root_associations
@object.each_with_object({}) do |item, hash|
serializer_for(item).embedded_in_root_associations.each_pair do |type, objects|
hash[type] = hash.fetch(type, []).concat(objects)
hash[type].uniq!
end
end
end
end
end