我正在使用Rails 4並設計,當我嘗試從我的管理控制檯(我使用Rails Admin)更新用戶時遇到問題。每次我嘗試更新,它給了我一個錯誤:index_users_on_unlock_token rails/devise中的唯一驗證錯誤
ActiveRecord::RecordNotUnique (PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_unlock_token"
這可能是因爲發生在unlock_token字段爲空大多數用戶使用。但是,當然可以爲空的字段仍然可以被索引?只有當用戶被鎖定在他們的帳戶權限之外時,纔會設置unlock_token?
我可以很容易地通過在確認令牌字段中輸入一個隨機字符串來避免這個問題,但這似乎是一個不好的方式來處理它。任何更好的想法?
我的用戶表的定義(當然,它的相關部分):
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "screen_name"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
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.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.integer "failed_attempts", default: 0
t.string "unlock_token"
t.datetime "locked_at"
end
錯誤從我的日誌:
SQL (10.5ms) UPDATE "users" SET "unlock_token" = $1, "updated_at" = $2 WHERE "users"."id" = 7 [["unlock_token", ""], ["updated_at", Mon, 24 Feb 2014 02:59:58 UTC +00:00]]
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_users_on_unlock_token"
DETAIL: Key (unlock_token)=() already exists.
是的,我認爲只有當用戶想要解鎖他們的賬戶並且應該允許多個NULL值用於唯一索引時,才設置unlock_token。你可以確認數據庫/版本(看起來像postgresql)。你可以從數據庫中顯示錶格定義嗎?另外,您更新用戶時的development.log消息是什麼? – Tim
謝謝蒂姆,我已經發布了上面的表格信息。開發日誌給出了與我上面提到的相同的錯誤,只是說鍵(空)已經存在 - 你需要完整的跟蹤嗎? psql --version給我9.1.3。奇怪的是 - 當我以該用戶身份登錄並更新其詳細信息時,它可以正常工作。只有當我以管理員身份登錄時纔會失敗(更新到rails管理員),更新另一個用戶的帳戶 – Dave
爲什麼您需要在該列上使用這樣的索引?另一件事,'NULL'被忽略了「然而,在這個比較中,兩個空值並不相等。」 – phoet