首页 > 解决方案 > 为什么每当我登录我的 Rails 应用程序时,我都会在“id”列中收到“PG::NotNullViolation null 值违反非空约束”?

问题描述

从 Heroku 转储、下载和 pg_restore 数据库后,每当我尝试登录我的 rails 应用程序时,都会出现上述错误。

不知何故,用户 id 似乎被视为 nil(即使我可以在数据库中看到 id 值)。

我还读到这可能是由于 id 是一个简单的 int 而不是一个序列,但是,正如您在我的架构中看到的那样:

create_table "users", id: :serial, force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
    t.string "last_name"
    t.string "provider"
    t.string "uid"
    t.boolean "admin", default: false, null: false
    t.boolean "affiliate_approved", default: false, null: false
    t.integer "cart_id"
    t.float "rev_share"
    t.boolean "notice", default: false, null: false
    t.string "iban"
    t.string "piva"
    t.string "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer "invitation_limit"
    t.string "invited_by_type"
    t.integer "invited_by_id"
    t.integer "invitations_count", default: 0
    t.string "username"
    t.string "slug"
    t.integer "enrolls_count", default: 0
    t.integer "partner_id"
    t.string "country"
    t.integer "referrer"
    t.boolean "gdpr_marketing"
    t.boolean "privacy_policy"
    t.boolean "subscription", default: false
    t.date "account_created_at"
    t.boolean "profilazione"
    t.boolean "terms_and_conditions"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["invitation_token"], name: "index_users_on_invitation_token", unique: true
    t.index ["invitations_count"], name: "index_users_on_invitations_count"
    t.index ["invited_by_id"], name: "index_users_on_invited_by_id"
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["username"], name: "index_users_on_username", unique: true
  end

似乎该 id 已用作序列号。

您知道可能出了什么问题吗?这个应用程序正在生产中,有数千名用户没有受到这个问题的影响,这让我觉得我的本地 PG 设置有问题。

编辑 - 完整的错误消息

PG::NotNullViolation at /auth/google_oauth2/callback
ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 9367, 127.0.0.1, 2018-09-17 09:51:59.463125, 2018-09-17 09:51:59.463125).

编辑 - 更多发现

在 user.rb (模型文件)中有一个 after_update 钩子,执行以下操作:

def change_log
  UserChange.create(ip_request: current_sign_in_ip, user: self)
end

这样我们就可以跟踪用户更改的所有内容及其 IP(GDPR 原因)。

将其注释掉后,一切正常,我的用户按计划登录

标签: ruby-on-railspostgresqlruby-on-rails-5

解决方案


必须有一个回调到另一个试图以空 ID 持续存在的表。检查任何相关表的回调和架构。在您的情况下,这是 UserChange 表。


推荐阅读