active_model_serializers/lib/active_model/serializer/adapter/json.rb
Guillermo Iguaran 19ac139880 Handle correctly null associations
null belongs_to associations are now serialized as nil instead
of raise an error during serialization.
2014-10-30 09:35:05 -05:00

35 lines
989 B
Ruby

module ActiveModel
class Serializer
class Adapter
class Json < Adapter
def serializable_hash(options = {})
if serializer.respond_to?(:each)
@result = serializer.map{|s| self.class.new(s).serializable_hash }
else
@result = serializer.attributes(options)
serializer.each_association do |name, association, opts|
if association.respond_to?(:each)
array_serializer = association
@result[name] = array_serializer.map { |item| item.attributes(opts) }
else
if association
@result[name] = association.attributes(options)
else
@result[name] = nil
end
end
end
end
if root = options.fetch(:root, serializer.json_key)
@result = { root => @result }
end
@result
end
end
end
end
end