At what point is validation triggered in the model when saving a file on S3 with Carrierwave and Fog?

53 Views Asked by At

There is an ActiveRecode model with a carrierwave uploader. I'm interested in the following question. At what point does validation occur? Before the moment the store method is triggered in the carrierwave uploader or after?

Here is an example of my model:

class File < ApplicationRecord
  mount_uploader :document, FileUploader

  validate :validate_file

  private

  def validate_file
    errors.add(:document, 'error')
  end
end

At what point does the validate_file method work? After CarrierWave places the file in storage or before?

1

There are 1 best solutions below

0
Milind On

Practically, there are two ways in which validation is triggered when you upload a file using Carrierwave -

  1. Before storing - before :store - what to do before file is uploaded, check the file type, change file name, check connection, check if user is authenticated, etc
  2. After storing - after :store - once file is uploaded what needs to be done - update the upload status in the table, send email, create background job, delete temp files, etc

You need to note one thing - nothing happens if you dont add the callbacks, file is uploaded directly wihtout any checks or validations.

To see the actual code, jump on this callbacks.rb file in carrierwave repo.