Rails 5 sqlite uuid 问题
Rails 5 uuid issue with sqlite
我正在转换我的 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',因为我打算在产品中使用 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 进行生产并且想使用 uuid。
我应该在 dev 中使用 pg 还是有其他方法?
SQLite 不是通用数据库,没有完全实现 SQL-92。您应该只将 SQLite 用于其设计目的(主要是启用软件、缓存...)。
如果你看看这里 Using UUIDs in SQLite 你会明白 SQLite 没有真正的 UUID
类型(BLOB(16)
是最好的选择).
正如Mu Is Too Short所说,你的开发平台和生产平台必须使用相同的环境,否则你会遇到很多麻烦......
我使用 Rails 5.2.1 和 sqlite3 让这个工作。
这是您需要的 (See this):
# config/application.rb
config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
仅通过以上,我在插入 sqlite3 时得到了相同的约束违规操作。修复是这样的 (See this, and related post)
# add this require in config/application.rb
require 'active_record/connection_adapters/sqlite3_adapter'
我正在转换我的 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',因为我打算在产品中使用 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 进行生产并且想使用 uuid。
我应该在 dev 中使用 pg 还是有其他方法?
SQLite 不是通用数据库,没有完全实现 SQL-92。您应该只将 SQLite 用于其设计目的(主要是启用软件、缓存...)。
如果你看看这里 Using UUIDs in SQLite 你会明白 SQLite 没有真正的 UUID
类型(BLOB(16)
是最好的选择).
正如Mu Is Too Short所说,你的开发平台和生产平台必须使用相同的环境,否则你会遇到很多麻烦......
我使用 Rails 5.2.1 和 sqlite3 让这个工作。
这是您需要的 (See this):
# config/application.rb
config.generators do |g|
g.orm :active_record, primary_key_type: :uuid
end
仅通过以上,我在插入 sqlite3 时得到了相同的约束违规操作。修复是这样的 (See this, and related post)
# add this require in config/application.rb
require 'active_record/connection_adapters/sqlite3_adapter'