Updating ActiveRecord Attachments in Rails

If you need to update an active record attachment that has been attached using has_one_attached relation with the parent model, you may encounter errors. Here’s an example:

1
2
3
4
5
# app/models/profile.rb

class Profile < ApplicationRecord
  has_one_attached :image
end

If an image is already attached to this profile model and we need to update it, we will do so by reattaching the image.

1
profile.image.attach(params[:image])

This will throw an error:

1
ActiveRecord::RecordNotSaved: Failed to remove the existing associated avatar_attachment. The record failed to save after its foreign key was set to nil.

This is because although we are replacing the image, we are leaving the original one orphaned, which will in turn fail foreign key constraints. The solution is to remove the first one and reattach it.

1
2
profile.image.purge
profile.image.attach(params[:image])

Now the updated image is attached!