2014-07-23 53 views
0

嗨在我的rails应用程序我使用devise和omniauth。在我有每当我使用Twitter,Facebook和LinkedIn认证一些奇怪的问题,同时任何一个正常工作另外一个是,如果这样的measn LinkedIn给这个错误设计omniauth数据库约束错误

SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO  "users" ("created_at", "provider", "uid", "updated_at") VALUES (?, ?, ?, ?) 

在用户mdoel

def self.from_omniauth(auth) 
     where(auth.slice(:provider, :uid)).first_or_create do |user| 
      user.provider =auth.provider 
      user.uid=auth.uid 
     end 
    end 

工作和

def self.from_omniauth(auth) 
     where(auth.slice(:provider, :uid)).first_or_create do |user| 
      user.provider =auth.provider 
      user.uid=auth.uid 
      user.email=auth.info.email 
     end 
    end 

如果像这样意味着微博正在工作,否则所有给出相同的错误我该怎么办?

回答

3

当Devise为用户表生成迁移时,它会在电子邮件地址中包含一个唯一索引。设计也设置模式,以便电子邮件默认为“”,而不是空。

因此,当您尝试保存无电子邮件记录时,它会找到一个电子邮件地址为“”的现有记录。由于电子邮件地址必须是唯一的,因此会引发错误。

您可以尝试更改模式,以使唯一性的工作方式稍有不同。例如:

class ChangeEmailUniqueness < ActiveRecord::Migration 
    def up 
    remove_index "users", :name =>"index_users_on_email" 
    add_index "users", ["email", "provider", "uid"], :name => "index_users_on_identity", :unique => true 
    end 

    def down 
    remove_index "users", :name => "index_users_on_identity" 
    add_index "users", ["email"], :name => "index_users_on_email", :unique => true 
    end 
end 

这并不完美,因为它可以让你有两个不同的供应商注册相同的电子邮件。

您也可以尝试这样的迁移:

class ChangeUserEmail < ActiveRecord::Migration 
    def change 
    change_column :users, :email, :string, null: true 
    end 
end 

这将允许电子邮件地址保存为空并且不会触发唯一的错误消息。