这是保存记录到postgres数据库在rails 3.2.12 &pg 9.3:
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
?如果不是,那么如何解决这个问题?
数据类型
smallserial
、serial
和bigserial
不是真正的类型,而仅仅是为了方便创建唯一标识符列(类似于其他一些数据库支持的AUTO_INCREMENT
属性)。
如果您的列是integer
,您不能将转换为serial
,但您可以模仿PostgreSQL所做的,就像您使用serial:
CREATE SEQUENCE tableame_colname _seq;ALTER TABLE tablename ALTER COLUMN colname SET DEFAULT nextval('tablename_colname_seq'::regclass);ALTER SEQUENCE tablename_colname_seq OWNED BY tablename_colname;
我在开发Rails 6应用程序时遇到过这样的问题。
我有一个User模型,用于创建student
和admin
:
class User < ApplicationRecord
belongs_to :role
end
和Role model:
class Role < ApplicationRecord
end
然而,我希望admin
和student
角色分别分配给每个admin
和student
,当它们被创建时,在表单中没有角色字段,所以我的模型是这样的:
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
Student model:
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
然后还更改了User模型,将role_id
作为可选的:
class User < ApplicationRecord
belongs_to :role, optional: true
end
。
希望这对你有帮助
我也遇到过类似的问题。
我来告诉你哪里出了问题,也许有人会对我的经验有所帮助
我有
ERROR: null value in column "created_at" violates not-null constraint
,问题是我有一个在before_create
和before_save
中运行的方法,这个方法试图保存小的更新。所以它尝试保存几次。
我的建议是检查你的代码在
before_save
中做什么andbefore_create
将optional: true
添加到我们要映射的模型
的例子:用户:
class User < ApplicationRecord
has_many :tasks
end
任务:class Task < ApplicationRecord
belongs_to :user, optional: true
end
set -----> null: true , in ur DB/migration/