Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveStorage File Attachment Validation

Is there a way to validate attachments with ActiveStorage? For example, if I want to validate the content type or the file size?

Something like Paperclip's approach would be great!

  validates_attachment_content_type :logo, content_type: /\Aimage\/.*\Z/
  validates_attachment_size :logo, less_than: 1.megabytes
like image 733
Tom Rossi Avatar asked Jan 08 '18 22:01

Tom Rossi


2 Answers

Well, it ain't pretty, but this may be necessary until they bake in some validation:

  validate :logo_validation

  def logo_validation
    if logo.attached?
      if logo.blob.byte_size > 1000000
        logo.purge
        errors[:base] << 'Too big'
      elsif !logo.blob.content_type.starts_with?('image/')
        logo.purge
        errors[:base] << 'Wrong format'
      end
    end
  end
like image 182
Tom Rossi Avatar answered Oct 16 '22 10:10

Tom Rossi


ActiveStorage doesn't support validations right now. According to https://github.com/rails/rails/issues/31656.


Update:

Rails 6 will support ActiveStorage validations.

https://github.com/rails/rails/commit/e8682c5bf051517b0b265e446aa1a7eccfd47bf7

Uploaded files assigned to a record are persisted to storage when the record
is saved instead of immediately.
In Rails 5.2, the following causes an uploaded file in `params[:avatar]` to
be stored:
```ruby
@user.avatar = params[:avatar]
```
In Rails 6, the uploaded file is stored when `@user` is successfully saved.
like image 19
swordray Avatar answered Oct 16 '22 12:10

swordray