February 24, 2021
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
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.
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
active_storage_variant_records table. The file should look
something like this:
class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0]def changecreate_table :active_storage_variant_records do |t|t.belongs_to :blob, null: false, index: falset.string :variation_digest, null: falset.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: truet.foreign_key :active_storage_blobs, column: :blob_idendendend
From here the fix is just to add a
uuid constraint for the id like so:
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|# ...endend
Now rollback your migrations, rerun your migrations, and onward to victory!!
Release notes: https://edgeguides.rubyonrails.org/6_1_release_notes.html
Upgrade guide: https://guides.rubyonrails.org/upgrading_ruby_on_rails.html
Written by Konnor Rogers who currently works at VeueLive as a full time developer. You should follow him on Twitter