Qwertie
Qwertie

Reputation: 6573

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?

Upvotes: 4

Views: 2471

Answers (1)

Rigi
Rigi

Reputation: 3500

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.

Upvotes: 6

Related Questions