Ruby on rails Rails和postgresql在创建记录时未正确对话
以下记录创建失败,因为Postgresql错误解释了数据Ruby on rails Rails和postgresql在创建记录时未正确对话,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,以下记录创建失败,因为Postgresql错误解释了数据 SQL (1.3ms) INSERT INTO "gruppomerceologicos" ("nome", "reparto_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["nome", "Salumeria"], ["reparto_id", 1], ["created_at", "2020-03-13 09:24:15.5294
SQL (1.3ms) INSERT INTO "gruppomerceologicos" ("nome", "reparto_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["nome", "Salumeria"], ["reparto_id", 1], ["created_at", "2020-03-13 09:24:15.529470"], ["updated_at", "2020-03-13 09:24:15.529470"]]
(0.2ms) ROLLBACK
Completed 500 Internal Server Error in 11ms (ActiveRecord: 2.5ms)
PG::NotNullViolation - ERROR: null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, Salumeria, 2020-03-13 09:24:15.52947, 2020-03-13 09:24:15.52947, 1).
行创建实际上是不正确的,因为PostgreSQL正在尝试处理id的null
值的记录
控制器是标准的
@gruppomerceologico = Gruppomerceologico.new(gruppomerceologico_params)
authorize @gruppomerceologico
@gruppomerceologico.save
respond_with(@gruppomerceologico)
然而,rails调试器确实显示它正在试图处理一个在错误发生点没有ID的记录
@gruppomerceologico
#<Gruppomerceologico id: nil, nome: "Salumeria", created_at: "2020-03-13 08:24:15", updated_at: "2020-03-13 08:24:15", reparto_id: 1>
通常Postgre知道它正在创建一个新记录,因此将分配顺序ID并创建该记录。但这并没有发生。rails和Postgresql之间的差距在哪里
最初的迁移:
class CreateGruppomerceologicos < ActiveRecord::Migration
def change
create_table :gruppomerceologicos do |t|
t.string :nome
t.timestamps null: false
end
end
end
当nextval
明显处于正常运行状态时。这两个数据库不知何故不同步。正如@sebastianPalmaselect nextval('gruppomerceologics_id_seq'::regclass)所建议的那样
将直接显示差异。创建gruppomerceologics
表的迁移是什么样子的?这是表检查的完整输出吗?它似乎缺少几个列,id列的默认值是多少?我更新了问题以添加该信息并刷新\d
信息。。。哦,我的。。。我的localhost数据库没有像开发服务器那样返回默认列。这是一个可能的解释吗?也许这就解释了问题,请尝试选择nextval('gruppomerceologics_id_seq':regclass)代码>在这两种环境中。宾果!在localhost上错误:关系“gruppomerceologics\u id\u seq”不存在,而在开发服务器上则不存在。我会编辑这个问题,这样这个案例可能会有用(尽管这并不能解释这个差异最初是如何产生的!)
class CreateGruppomerceologicos < ActiveRecord::Migration
def change
create_table :gruppomerceologicos do |t|
t.string :nome
t.timestamps null: false
end
end
end
class AddRepartoToGruppomerceologicos < ActiveRecord::Migration
def change
add_reference :gruppomerceologicos, :reparto, index: true, foreign_key: true
end
end
Table "public.gruppomerceologicos"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+-------------------------------------------------
id | integer | | not null | nextval('gruppomerceologicos_id_seq'::regclass)
nome | character varying | | |
created_at | timestamp without time zone | | not null |
updated_at | timestamp without time zone | | not null |