2

I'm converting my rails 5.1 app to start using UUID instead of incremental ids as the default active_record.

I've changed my migration files to use id: :uuid

class CreateProjects < ActiveRecord::Migration[5.1]
  def change
    create_table :projects, id: :uuid do |t|
      t.string :title
      t.text :description

      t.timestamps
    end
  end
end

I've added a migration file to support 'uuid-ossp' and 'pgcrypto' as I intend to use pg in prod.

class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
  def change
    enable_extension 'uuid-ossp'
    enable_extension 'pgcrypto'
  end
end

But when I try to create an object, I get an error as if the id was null.

ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: projects.id: INSERT INTO "projects" ("created_at", "updated_at") VALUES (?, ?)

the schema.rb offers a hint that 'uuid' is not a known type

# Could not dump table "projects" because of following StandardError
#   Unknown type 'uuid' for column 'id'

I suggest I could start using string types instead of uuid for sqlite3, but I intend on using postgres for production and would like to use uuids.

Should I use pg in dev or is there another way ?

rapdev
  • 81
  • 1
  • 8
  • 2
    If you intend on using PostgreSQL in production then you really need to use it in your development and testing environments as well. There are so many differences between PostgreSQL and SQLite that Rails cannot and will not protect you from that not using the same database in all three environments is madness. A minor data type issue like this will be the least of your concerns. – mu is too short Nov 11 '17 at 22:22

2 Answers2

0

SQLite is not a generic DB and don't fully implement SQL-92. You should only use SQLite for it's designed purpose (mostly enable software, caching,...).

If you take a look here Using UUIDs in SQLite you'll understand that SQLite don't have a real UUID type (a BLOB(16) is the best choice).

As said by Mu Is Too Short, you must use the same environment between your development platform and the production one, or you'll facing a lot of trouble...

Blag
  • 5,818
  • 2
  • 22
  • 45
-3

I got this to work using Rails 5.2.1 and sqlite3.

Here's what you need (See this):

# config/application.rb
config.generators do |g|
  g.orm :active_record, primary_key_type: :uuid
end

With only the above, I got the same constraint violation op got when inserting into sqlite3. The fix was this (See this, and related post)

# add this require in config/application.rb
require 'active_record/connection_adapters/sqlite3_adapter'
jgo
  • 1