2017-03-26 147 views
0

的用戶名在我的應用程序像documentation描述我更新設計出應對使用:username代替:email作爲驗證。我想:username獨特:email不是唯一的用戶註冊與設計

註冊與:username工作正常。但是,如果後來我想更新我的帳戶,並招來了不潮頭電子郵件軌拋出我下面的錯誤:

SQLite3::ConstraintException: UNIQUE constraint failed: users.email: UPDATE "users" SET "email" = ?, "updated_at" = ? WHERE "users"."id" = ? 

缺少什麼我在這裏? 此外,我在我的user.rb中爲用戶名添加了驗證程序,因爲沒有它,可以保存相同的用戶名。有沒有更「設計」的做法呢?

user.rb

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :rememberable, :trackable, :validatable 

    validates :username, uniqueness: true 


    def email_required? 
    false 
    end 

    def email_changed? 
    false 
    end 
end 

schema.rb

create_table "users", 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 "username" 
    end 

    add_index "users", ["email"], name: "index_users_on_email", unique: true 
    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 

回答

1

你做的一切權利。你遵循的文件也是正確的。

你需要額外的在你的情況下,只有一點是不唯一的電子郵件。如果您查看設計遷移here,您可以看到電子郵件在數據庫級別也是唯一需要的。

那麼,你是在數據庫級別收到錯誤。爲了擺脫這個問題,你需要手動刪除用戶郵件表中的唯一約束。

+0

好的。聽起來合乎邏輯。我是否也需要整個「add_index」用戶,...「 - 」用戶名「的東西呢?因爲我的第二個問題(關於唯一性驗證程序)。 – Oliver

+0

如果你想要db級別檢查用戶名也是。對於特定的導軌,它不是必需的。因爲您已經在模型中添加了唯一性驗證。 –

1

你得到的是一個數據庫級錯誤,你可以在schema.rb文件中看到,email的索引已經實現了unique: true密鑰。我認爲你必須編輯Devise遷移或創建新的並刪除唯一約束。