This happens because the Serializer.attributes
method call each field using the ActiveModel.read_attribute
method. This method will apply some validations, like validates_presence_of
at the model's definition, that will raise the exception. To avoid it I give three bad solutions and after a better and simple one:
- Change the model definition, but you will miss your validation.
- Overwrite the method
ActiveModel.read_attribute
to handle this behavior, you will get new challenges.
- Overwrite the
Serializer.attributes
and instead of call super, call object.attributes
.
But the best option will be create a new serialize class, to avoid besides effects, with the only fields that you want. Then specify this at the controller class:
render json: People.all.reduced, each_serializer: SimplePersonSerializer
Edit 1
The right answer should be the one from Maurício Linhares.
render json: result.to_json( only: array_of_fields )