'Make Active Storage has_one_attatched not null

I have a model with active storage set up with has_one_attached and some users have hit submit without adding a file to the form. Before I add a validation to the frontend I want to make sure that the backend will reject a record if it does not have an attached file.

How can I set up a model so it will not save unless an active storage has_one_attached has something in it?



Solution 1:[1]

I think, that for now, the only option would be to follow the 'regular' path: add include ActiveModel::Validations and validates_with QwertieCustomValidator to your model, create custom validator under app/validators and down there check if record.attached_file.attached?, if no, add errors with: record.errors.add(:attached_file, 'no file was attached')

On second thought, you don't need to specify validator in other file, I just did it in my project to match adapted project's flow. The shortest way would look like this:

has_one_attached :attached_file

validate :check_file_presence

def check_file_presence
  errors.add(:attached_file, "no file added") unless attached_file.attached?
end

Hope that helps you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thank_you