以下是将记录保存到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
?如果不是,那么如何解决这个问题?
发布于 2020-08-07 09:08:12
在使用Rails6应用程序时,我遇到了类似的问题。
我有一个用于创建student
和admin
的用户模型
class User < ApplicationRecord
belongs_to :role
end
和Role模型:
class Role < ApplicationRecord
end
但是,我希望在创建表单时为每个admin
和student
分别分配student
和admin
角色,而表单中没有roles字段,因此我的模型如下所示:
管理员模型:
class Admin < ApplicationRecord
before_save :set_admin_role
belongs_to :user
private
def set_admin_role
# set role_id to '1' except if role_id is not empty
user.role_id = '1' if user.role_id.nil?
end
end
学生模型:
class Student < ApplicationRecord
before_save :set_student_role
belongs_to :user
private
def set_student_role
# set role_id to '2' except if role_id is not empty
user.role_id = '2' if user.role_id.nil?
end
end
因此,每当我尝试创建管理员和学生时,都会抛出错误:
ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR: null value in column "role_id" violates not-null constraint)
这里是我如何解决它的
问题是在我的迁移文件中,users
表中的role_id
被设置为null: false
。我不得不把它改成null: true
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.references :role, null: true, foreign_key: true
t.timestamps
end
end
end
然后还更改了用户模型,使role_id
成为可选的:
class User < ApplicationRecord
belongs_to :role, optional: true
end
就这样。
我希望这对有帮助
发布于 2020-08-19 18:35:07
我也遇到过类似的问题。
我会告诉你哪里出了问题,也许有人会发现我的经验很有用
我有ERROR: null value in column "created_at" violates not-null constraint
问题是,我有一个在before_create
和before_save
中运行的方法,这些方法试图通过较小的更新来保存。所以它试着节省了几次。
我的建议是检查您的代码在before_save
和before_create
中执行的操作
https://stackoverflow.com/questions/24298171
复制