ActiveStorage attach is successful, but the blob disappears from database

Something weird is happening…

A Rails application has a Post model which has_many_attached :images:

class Post < ApplicationRecord
  has_many_attached :images do |attachable|
    attachable.variant :medium, resize_to_fit: [800, 1600]
  end
  
  validates :images, processable_file: true, content_type: ['image/png', 'image/jpeg'], size: { less_than: 10.megabytes }

Then the images are uploaded by the user one at a time and this is the controller action:

  def attach_image
    @post = current_user.posts.find(params[:id])
    if @post.images.attach params[:image]
      @image = @post.images.last
      render json: { success: 1, file: { url: url_for(@image.variant(:medium)), image_id: @image.id } }, status: :created
    else
      render json: { success: 0 }, status: :unprocessable_entity
    end
  end

This usually works as expected, but sometimes the response is successful and a URL for the image is returned. However that URL doesn’t work and the image is not displayed (404).

I decoded the image URL (which is an ActiveStorage URL) and I find the blob_id: that blob_id doesn’t exist in the database. How is that even possible?

It seems that attach returns a truthy value, url_for generates a URL for the image successfully… even if the image (blob) has not been saved to the database.