When is ActiveStorage::IntegrityError raised?

Viewed 8558

My app (locally) raises ActiveStorage::IntegrityError error, whenever it tries to attach a file. How can I get out of this error?

I have only one has_one_attached and I don't know how that error gets in the way.

# model
has_one_attached :it_file
Tempfile.open do |temp_file|
  # ...
  it_file.attach(io: temp_file, filename: 'filename.csv', content_type: 'text/csv')
end

# storage.yml
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

EDIT: it can be related with deleting storage/ directory (it happened after I deleted that) or it can be because it's happening in a job (the full error was Error performing ActivityJob (Job ID: .. ) from Async( .. ) in .. ms: ActiveStorage::IntegrityError (ActiveStorage::IntegrityError)

And this does not add files to storage/ folder but it's generating folders under it when I tried to attach them.

3 Answers

As mentioned in the comments, one reason this can happen is that the file object is at the end of the file, which was the problem in this case. It could be fixed here with temp_file.rewind.

Very weird. After update to rails 6.0 I must recalculate some checksums. Yes I used dokku,docker. It was fine before update.

# Disk service is in use for ActiveStorage
class ProjectImage < ApplicationRecord
  has_one_attached :attachment
end

# update all checksums
ProjectImage.all.each do |image|
  blob = image.attachment.blob
  blob.update_column(:checksum, Digest::MD5.base64digest(File.read(blob.service.path_for(blob.key))))
end;

This was happening to me not because of anything mentioned above.

In my case I was defining a test var using one dummy file, but I was attaching it to 2 different records.

let(:file) { File.open(Rails.root.join('spec', 'fixtures', 'files', 'en.yml')) }
let(:data) { [file, file] }

The function in question received a list of ids and data and attaching the files to the records. This is a simplified version of the code

record_0.file.attach(
  io: data[0],
  filename: 'en.yml',
  content_type: 'application/x-yaml'
)
record_1.file.attach(
  io: data[1],
  filename: 'en.yml',
  content_type: 'application/x-yaml'
)

Once I defined 2 test vars, one for each record, using the same file I got it to work.

let(:file_0) { File.open(Rails.root.join('spec', 'fixtures', 'files', 'en.yml')) }
let(:file_1) { File.open(Rails.root.join('spec', 'fixtures', 'files', 'en.yml')) }
let(:data) { [file_0, file_1] }
Related