Konnor's Blog

Active Storage Variants with Rails 6.1

February 24, 2021

The Error!

Upgrading to Rails 6.1 and encountering the following error?

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column “record_id” of relation “active_storage_attachments” violates not-null constraint)

Let me save you a couple hours!

Lets back up a step. Are you using t.uuid :record_id (is your record_id for ActiveStorage a uuid?)

If you’re not sure, you can check your db/schema.rb

db/schema.rb
create_table "active_storage_attachments", force: :cascade do |t|
# ...
t.uuid "record_id", null: false
# ...
end

If yes, keep reading. If not, sorry, this wont be much help.

Using UUID for record_id, cool I was too

Alright now that we’ve located the source how do we fix it?

When you run rails app:update or rails active_storage:update it will create 2 migrations for you. In particular we want to look at the one generating the active_storage_variant_records table. The file should look something like this:

db/migrate/xxxx_create_active_storage_variant_records.active_storage.rb
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0]
def change
create_table :active_storage_variant_records do |t|
t.belongs_to :blob, null: false, index: false
t.string :variation_digest, null: false
t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end
end

From here the fix is just to add a uuid constraint for the id like so:

db/migrate/xxxx_create_active_storage_variant_records.active_storage.rb
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0]
def change
- create_table :active_storage_variant_records do |t|
+ create_table :active_storage_variant_records, id: :uuid do |t|
# ...
end
end

Now rollback your migrations, rerun your migrations, and onward to victory!!

Active Storage docs

Rails 6.1 migration docs


Written by Konnor Rogers who currently works at VeueLive as a full time developer. You should follow him on Twitter