我认为这个问题与将类的primary_key设置为tagid有关,这将导致MySQL自动增加id值而不是postgres。不是100%肯定。请求帮助
我们有一个MySQL Rails应用程序,我们正在考虑迁移到Postgres。在我们播种的地方有一部分我们有以下内容:
class Tab < ActiveRecord::Base
self.primary_key = "tagid"
def self.rebuild_db
terms=self.terms
Tag.delete_all
terms.each do |term|
Tag.create! tagid: term[:tag_id], phrase: term[:phrase], tag_string: term[:tag_string]
end
end
从控制台调用时,出现以下错误:
> [1] pry(main)> Tag.rebuild_db
> SQL (12.9ms) DELETE FROM "tags"
> (0.3ms) BEGIN
> SQL (2.3ms) INSERT INTO "tags" ("created_at", "id", "is_location_type", "phrase", "tag_string", "tagid", "updated_at")
> VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "tagid" [["created_at",
> Tue, 17 Mar 2015 09:31:27 PDT -07:00], ["id", nil],
> ["is_location_type", nil], ["phrase", "food"], ["tag_string", "-1-"],
> ["tagid", 1], ["updated_at", Tue, 17 Mar 2015 09:31:27 PDT -07:00]]
> (0.2ms) ROLLBACK
> ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint
> DETAIL: Failing row contains (null, food, 2015-03-17 16:31:27.235545, 2015-03-17 16:31:27.235545, null, 1, -1-).
> : INSERT INTO "tags" ("created_at", "id", "is_location_type", "phrase", "tag_string", "tagid", "updated_at") VALUES ($1, $2, $3, $4,
> $5, $6, $7) RETURNING "tagid"
我明显看到id = nil,但我不确定我是否做错了。这是我们迄今为止唯一的问题所以我希望这是一个简单易行的问题。为什么我会收到此错误,我将如何解决? THX
表结构如下:
embers_dev=# \d+ tags
Table "public.tags"
Column | Type | Modifiers | Storage | Stats target | Description
------------------+-----------------------------+---------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('tags_id_seq'::regclass) | plain | |
phrase | character varying(255) | | extended | |
created_at | timestamp without time zone | not null | plain | |
updated_at | timestamp without time zone | not null | plain | |
is_location_type | boolean | | plain | |
tagid | integer | | plain | |
tag_string | character varying(255) | default ''::character varying | extended | |
Indexes:
"tags_pkey" PRIMARY KEY, btree (id)
[3] pry(main)> Tag.where(id: nil)
Tag Load (0.4ms) SELECT "tags".* FROM "tags" WHERE "tags"."id" IS NULL
=> []
[4] pry(main)>