ruby-on-railspg

ERROR: PG::NotNullViolation: ERROR: null value in column "service_name" violates not-null constraint after upgrade Rails to 7.0.6


Recently we had upgraded the Ruby on Rails app (Ruby 2.7.2 to 3.2 , Rails 5.2 to 7.0.6). After upgraded the versions, tested in local it was working as we expected, then we deployed the project into Heroku staging environment. When calling delayed jobs, while attachment saving getting below error

PG::NotNullViolation: ERROR:  null value in column \"service_name\" of relation \"active_storage_blobs\" violates not-null constraint
DETAIL:  Failing row contains (7713, qNKYpuwA1jQZa4i37gRu8A4N, Stagetech1_0308, application/pdf, {\"identified\":true}, 210599, dmcDLApGSoTMuSfLCm5/0w==, 2023-08-03 15:58:36.169884, null).
: INSERT INTO \"active_storage_blobs\" (\"key\", \"filename\", \"content_type\", \"metadata\", \"byte_size\", \"checksum\", \"created_at\") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING \"id\"".

Tried active storage installation and rails db:migrate. but getting the same error.

Can anyone help how can I fix it?


Solution

  • Active Storage uses the :service_name attribute in the active_storage_blobs table to support multiple services. This service_name attribute isn't nullable. If you haven't updated your database schema, Rails will attempt to insert null for this value and you'll get the error you're seeing.

    You can try to run the following to populate db

    rails active_storage:update
    rails db:migrate
    

    if not then maybe you can try to populate service_name by yourself to local, amazon, etc

    class BackfillServiceNameInActiveStorageBlobs < ActiveRecord::Migration[7.0]
      def up
        ActiveStorage::Blob.unscoped.where(service_name: nil).in_batches.update_all(service_name: "local")
      end
    
      def down
        # No need to rollback
      end
    end