rails: Cannot Serialize Object with no ActiveStorage Attachment to JSON
Steps to reproduce
class Foo
has_one_attached :image
end
Foo.new.as_json
Expected behavior
The serialized Foo.new should have an image field that is specified as nil, signifying that it has no attached image.
Actual behavior
Module::DelegationError: to_model delegated to attachment, but attachment is nil
System configuration
Rails version: 5.2.0
Ruby version: 2.5.1
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 5
- Comments: 18 (7 by maintainers)
I’m aware that we can get some workarounds by manipulating the
as_jsonoutput, but I don’t think basic serialization should require that.i use as_json with inclusion of methods from model
Man, I’m learning ruby… I did not know about the
defmethod for defining properties. Thank you!It’s going to be fixed eventually.
try to change with this on serializer :
Note that this is a problem only with
has_one_attachedrelationships not withhas_many_attachedones. Here is the workaround I came up with (I usejsonapi-rbfor serialisation). A bit tedious but does the job.model:
controller: