23

One of my Rails migrations uses a uuid as the primary key. The Postgres extension gen_random_uuid() should solve this issue, but I continue to get the error after installing the relevant extension (uuid-ossp).

mu is too short
  • 426,620
  • 70
  • 833
  • 800
user3006381
  • 2,735
  • 3
  • 23
  • 32

4 Answers4

47

The issue was that the uuid-ossp extension was being blown away with the database each time I dropped the db as part of a reset and migration (e.g. rake db:drop db:create db:migrate).

The fix is to create a migration that's run before all other migrations which enables the relevant extension(s). Like so (db/migrate/0_enable_extensions.rb):

class EnableExtensions < ActiveRecord::Migration[5.1]
  def change
    enable_extension 'uuid-ossp'
    enable_extension 'pgcrypto'
  end
end
user3006381
  • 2,735
  • 3
  • 23
  • 32
2

I got the same error after generating a model with uuid as primary key like this:

rails g scaffold user name --primary-key-type=uuid

I'd forgotten to load the pgcrypto extension in the migration file.

Solution:

Just add this

enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')

to the migration file like so:

class CreateUsers < ActiveRecord::Migration[7.0]
  enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto') # <-- HERE
  def change
    create_table :users, id: :uuid do |t|
      t.string :name
      t.timestamps
    end
  end
end

Then rake db:migrate will succeed.

stevec
  • 41,291
  • 27
  • 223
  • 311
  • This requires the database user, as per "username" in config/database.yml, to have the superuser role. To do so, run ALTER ROLE username SUPERUSER as postgres user. If you do not want to assign this role to the db user, log in as postgresql, connect to the db in question and run CREATE EXTENSION pgcrypto; – Andreas Gebhard Aug 15 '22 at 16:29
0

Edge case answer:

Add the migration enabling the extension as stated above.

If you've previously had bigint id's and you're converting over to UUID, running rake db:reset db:migrate failed for me. Be sure to run rake db:drop db:create db:migrate as stated above!

If you get the error Environment data not found in the schema, run bin/rails db:environment:set RAILS_ENV=development.

Stone
  • 2,608
  • 26
  • 26
0

This error hit me hard even though I was having both uuid-ossp & pgcrypto extension. After lot of hit & trial method figured out the fix.

For me it was multiple database that were present and was few migrations were pending in non-default database. To fix I simply ran

RAILS_ENV=development rails db:drop:all
RAILS_ENV=development rails db:create:all
RAILS_ENV=development rails db:migrate:all

And same for the test env.

RAILS_ENV=test rails db:drop:all
RAILS_ENV=test rails db:create:all
RAILS_ENV=test rails db:migrate:all

Hope this helps to people working on multiple db's.

prashant
  • 2,808
  • 5
  • 26
  • 41