Hey everyone!
It seems this has been open for a while, and as per George’s last statement I’m assuming a pull request is still welcome? If so I’ve been working on this the past few days
(As a small side note, there does already seem to be a PR open but I provided my thoughts on that here. I believe Igor responded in support as well)
I had a question about the :presence
validator.
The Issue
I assume we want validates :avatar, presence: true to validate that a ::Blob is actually attached. However activestorage attachments don’t work like standard model fields: all changes to attachments and blobs are processed after the record itself is saved (for good reason).
This unfortunately means any validations for :presence run at a time when the attachment changes (stored in @attachment_changes) have not yet been applied.
Potential Workaround + Another Issue
One workaround would be to have the validator look at what changes are queued up to be applied and decide if an attachment is expected to be present or blank after the record is saved.
This would work well, but the :detach, :purge, and :purge_later throw a wrench in this logic. They immediately delete the attachments (or at least queue them up for deletion) before setting the attachment to nil. So when the record is finally validated later it might fail :presence validations but it’s too late because the association ::Attachment/::Blob records are already destroyed.
All this makes what should be a “simple” presence check much more complex because of the nature of how attachments are stored. Unless I’m missing an obvious solution, which I might be!
My personal thought: If we want attachments to feel like true model fields then the validation should be performed first and the deletion should be blocked/avoided if the validation fails. (And of course, users can always bypass validations as needed).
Would love to hear your thoughts. In the mean time, I’m happy to implement the size and content type validations.
As always, thanks for everyone’s time here. As an avid Rails user, everyone’s contribution is much appreciated.