ruby-on-rails - Rails:PG::NotNullViolation:错误:列 "id"中的空值违反了非空约束

标签 ruby-on-rails postgresql

这是在 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 表后。我们发现表中的 idinteger。我们还发现其他表上的 Idserial。看来 id 应该是 serial 这样它就可以自动递增了。如果是,那么如何将 id 列从 integer 转换为 serial?如果不是,那么如何解决这个问题?

最佳答案

The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).

如果您的列是一个整数,您不能将它转换序列,但您可以模仿,PostgreSQL 会做的,只是就像您使用序列号创建表格一样:

CREATE SEQUENCE tablename_colname_seq;
ALTER TABLE tablename ALTER COLUMN colname SET DEFAULT nextval('tablename_colname_seq'::regclass);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

关于ruby-on-rails - Rails:PG::NotNullViolation:错误:列 "id"中的空值违反了非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24298171/

相关文章:

postgresql - Postgres NestJS Prisma 迁移 - 数据库错误代码 : 23502 column of relation contains null values

postgresql - PostgreSQL 函数中是否有命名参数的约定

sql - CTE真的是一种观点吗?

c# - 无法将数据库类型 tsvector 转换为 String

mysql - Ruby Rails,在索引erb页面中获取db中列的重复计数

ruby-on-rails - 如何避免 Rails 中的 BREACH 攻击?

ruby-on-rails - 更优雅地处理项目中的 Redis 需求?

postgresql - 如何使用 ecto 查询表达式在 3 个表之间连接和过滤

ruby-on-rails - 如何在 RoR 中调用方法并发送新参数?

ruby-on-rails - 部署后我看到标准 nginx 的 "It works!"