ERROR: null value in column “id” violates not-null constraint

。_饼干妹妹 提交于 2019-12-10 16:04:42

问题


I just migrated my app from mysql to postgres but when I try to insert a record in a specific table I get violates not-null constraint error:

ERROR:  null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 1, 1, null, null, null, 2016-03-09 09:24:12.841891, 2012-12-31 23:00:00, 2012-12-31 23:00:00, null, null, f, null, f, XYZAssignment, null, null, null, null).

********** Error **********

    ERROR: null value in column "id" violates not-null constraint
    SQL state: 23502
    Detail: Failing row contains (null, 1, 1, null, null, null, 2016-03-09 09:24:12.841891, 2012-12-31 23:00:00, 2012-12-31 23:00:00, null, null, f, null, f, XYZAssignment, null, null, null, null).

When I try to create the record using factory_girl:

@assignment = FactoryGirl.create(:assignment)

It builds this sql query:

INSERT INTO assignments(
            id, account_id, l_id, viewed_at, accepted_at, declined_at, 
            expires_at, created_at, updated_at, decline_reason, decline_reason_text, 
            promotion, c_checked_at, forwardable, type, f_promo, 
            c_check_successful, c_check_api_result, c_check_human_result)
    VALUES (null, 1, 1, null, null, null, '2016-03-09 09:24:12.841891', '2012-12-31 23:00:00', '2012-12-31 23:00:00', null, null, 'f', null, 'f', 'XYZAssignment', null, null, null, null);

This is the assignment factory:

FactoryGirl.define do
  factory :assignment do
    expires_at 24.hours.from_now
    account
    lead
  end
end

this is the table description:

CREATE TABLE assignments(
  id serial NOT NULL,  account_id integer NOT NULL,  l_id integer NOT NULL,  viewed_at timestamp without time zone,  accepted_at timestamp without time zone,  declined_at timestamp without time zone,  expires_at timestamp without time zone,  created_at timestamp without time zone,  updated_at timestamp without time zone,  decline_reason character varying(16),  decline_reason_text character varying(256),  promotion boolean NOT NULL DEFAULT false,  c_checked_at timestamp without time zone,  forwardable boolean DEFAULT true,  type character varying(64),  f_promo boolean,  c_check_successful boolean,  c_check_api_result character varying(32),  c_check_human_result character varying(32),  CONSTRAINT assignments_pkey PRIMARY KEY (id)
) WITH (
  OIDS=FALSE
);

Looks its not able to auto increment the id, any idea?


回答1:


You have to skip id in the INSERT operation:

INSERT INTO assignments(account_id, l_id, ...) 
VALUES
(1, 1, ...)

The id will automatically get the next sequence number, since it is an auto-increment field.



来源:https://stackoverflow.com/questions/35864021/error-null-value-in-column-id-violates-not-null-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!