This is because the Serializer.attributes method calls each field using the ActiveModel.read_attribute method. This method will apply some validations, such as validates_presence_of in the model definition, which will throw an exception. To avoid this, I give three bad decisions, and after that the best and simplest:
- Change the model definition, but you will skip your test.
- Overwrite the
ActiveModel.read_attribute method to deal with this behavior, you will get new problems. - Overwrite
Serializer.attributes and instead of calling super call object.attributes .
But the best option would be to create a new serialization class to avoid, in addition to effects, with the only fields you want. Then specify this in the controller class:
render json: People.all.reduced, each_serializer: SimplePersonSerializer
Change 1
The correct answer should be one of Mauricio Linares .
render json: result.to_json( only: array_of_fields )
source share