Search code examples
ruby-on-railsactiverecordattachmentrails-activestorage

Rails 6 Active Storage: Could not find or build blob: expected attachable... (issue when (re)setting attachment)


In my application it is possible for an admin user to suggest and edit to another user's profile. I would like for the admin user to be able to suggest a (new) avatar for the non-admin user. Currently my user (user = spkr in my application) model has:

has_one_attached :image
has_one_attached :edited_image

Where image is the avatar image chosen by the user, and edited_image is the the avatar image suggested by the admin user.

When using the admin 'update' form, the edited_image is set

if spkr_params[:edited_image].present?
  @spkr.edited_image = spkr_params[:edited_image]
end

This successfully sets an attachment as edited_image.

When an admin user submits an edit non-admin user receives a confirmation email. When clicked I would like the image of the non-admin user to update.

...
if @spkr.edited_image.present?
   @spkr.image.purge
   @spkr.image = @spkr.edited_image
end
@spkr.save!

However I get the following error which raises on @spkr.save!:

Could not find or build blob: expected attachable, got #<ActiveStorage::Attached::One:0x00007fdcc44fa440 @name="edited_image", @record=#<Spkr id: 154... >>

Which is the edited_image from the @spkr:

@spkr.edited_image
=> #<ActiveStorage::Attached::One:0x00007fdcc44fa440 @name="edited_image", @record=#<Spkr id: 154...>>

My feeling is that @spkr.edited_image is not the 'attachable part' of @spkr.edited_image, but I am unsure how to resolve this.

Thank you for any help.


Solution

  • I solved this by replacing the line

    @spkr.image = @spkr.edited_image
    

    with

    @spkr.image = @spkr.edited_image.blob
    

    This also worked:

    @spkr.image.attach(@spkr.edited_image.blob)