【发布时间】:2022-04-01 18:05:00
【问题描述】:
以下是在 rails 3.2.12 和 pg 9.3 上将记录保存到 postgres 数据库时的错误:
ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint
: INSERT INTO "sw_module_infox_module_infos" ("about_controller", "about_init", "about_log", "about_misc_def", "about_model", "about_onboard_data", "about_subaction", "about_view", "about_workflow", "active", "api_spec", "category_id", "created_at", "last_updated_by_id", "module_desp", "name", "submit_date", "submitted_by_id", "updated_at", "version", "wf_state") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) RETURNING "id"):
activerecord (3.2.12) lib/active_record/connection_adapters/postgresql_adapter.rb:1166:in `get_last_result'
activerecord (3.2.12) lib/active_record/connection_adapters/postgresql_adapter.rb:1166:in `exec_cache'
到目前为止,该表工作正常(在今天出现错误之前保存了大约 50 条记录)。在 pgadmin 中打开 pg 表后。我们发现桌子上的id 是integer。我们还发现另一张桌子上的Id 是serial。似乎 id 应该是 serial 所以它可以自动递增。如果是,那么如何将 id 列从integer 转换为serial?如果不是,那么如何解决这个问题?
【问题讨论】:
-
"serial" 只是
INTEGER的别名,带有DEFAULT nextval('some_sequence');请参阅用户手册。 -
表是使用 rails rake db:migrate 创建的。 33 个表中约有 8 个具有整数类型。其余的是串行的。有些表也缺少索引。不知道是什么导致了postgres的问题。 sqlite创建的同一张表完全没有这个问题。