Active_model_serializers: Rendering a nil object with a custom serializer fails

Created on 7 Jul 2016  路  1Comment  路  Source: rails-api/active_model_serializers

Updating from 0.9.5 to 0.10.2, encountering error when custom serializer attempts to render a nil object

Seems to be the same error as closed issue #204. Is this error now the expected behavior?

Expected behavior vs actual behavior

Given

foo = some_function_that_may_return_nil
json = CustomFooSerializer.new(foo)

Expected
json equals nil

Actual
Error: undefined method 'read_attribute_for_serialization' for nil:NilClass

Steps to reproduce

class CustomFooSerializer < ActiveModel::Serializer
  attributes  :id, :name, :bar
end

CustomFooSerializer.new(nil) throws error.

Question

>All comments

Serializers expect records. We can't stop you from passing in nil. It's outside the scope of AMS to prevent users passing in the wrong data type for a serializer.

If you have something that may be nil, do a nil check or use SerializableResource

Anything else come up in the upgrade? Please feel free to continue discussion here.

Was this page helpful?
0 / 5 - 0 ratings