【发布时间】:2017-11-11 22:01:05
【问题描述】:
我正在转换我的 rails 5.1 应用程序以开始使用 UUID 而不是增量 ID 作为默认的 active_record。
我已将迁移文件更改为使用 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
我已经添加了一个迁移文件来支持“uuid-ossp”和“pgcrypto”,因为我打算在 prod 中使用 pg。
class EnablePgcryptoExtension < ActiveRecord::Migration[5.1]
def change
enable_extension 'uuid-ossp'
enable_extension 'pgcrypto'
end
end
但是当我尝试创建一个对象时,我收到一个错误,好像 id 为空一样。
ActiveRecord::NotNullViolation: SQLite3::ConstraintException: NOT NULL constraint failed: projects.id: INSERT INTO "projects" ("created_at", "updated_at") VALUES (?, ?)
schema.rb 提示“uuid”不是已知类型
# Could not dump table "projects" because of following StandardError
# Unknown type 'uuid' for column 'id'
我建议我可以开始对 sqlite3 使用字符串类型而不是 uuid,但我打算将 postgres 用于生产并希望使用 uuids。
我应该在 dev 中使用 pg 还是有其他方法?
【问题讨论】:
-
如果你打算在生产环境中使用 PostgreSQL,那么你真的需要在你的开发和测试环境中使用它。 PostgreSQL 和 SQLite 之间有很多差异,Rails 不能也不会保护您免受在所有三种环境中不使用同一个数据库是疯狂的。像这样的次要数据类型问题将是您最不关心的问题。
标签: ruby-on-rails postgresql sqlite uuid