active_model_serializers icon indicating copy to clipboard operation
active_model_serializers copied to clipboard

0.10.x: has_one does not include attribute when value is nil

Open patrick99e99 opened this issue 8 years ago • 0 comments

class MySerializer ActiveModel::Serializer
   attribute :name
   has_one :parent, :serializer => MySerializer
end

Expected behavior vs actual behavior

I expect that when I serialize an object without a parent that I will get the json: { name: 'the child, parent: { name: 'the parent', parent: null } }

but what I actually get is: { name: 'the child, parent: { name: 'the parent' } }

... In order to get around this behavior, I am having to do (which I would prefer to not have to do):

class MySerializer ActiveModel::Serializer
   attribute :name, :parent
   
  def parent
    MySerializer.new(object.parent) if object.parent
  end
end

and then I get my desired output (which was the behavior of 0.8.x)

patrick99e99 avatar Apr 12 '17 18:04 patrick99e99