如何防止在我的Rails应用程序中创建重复的用户?

时间:2016-05-10 20:11:43

标签: ruby-on-rails ruby-on-rails-4 google-oauth oauth2

我正在使用Rails 4.2.3。我想使用Google和Facebook在我的系统中验证(和创建)用户。所以我在app / models / user.rb文件中有这个...

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

上面的问题是我的数据库中是否有一行,如下所示

 id |   provider    |          uid          |     name      | oauth_token | oauth_expires_at |         created_at         |         updated_at         |          email          
----+---------------+-----------------------+---------------+-------------+------------------+----------------------------+----------------------------+-------------------------
  5 | google-oauth2 | 777711643329020555465 | Dave A        |             |                  | 2016-05-10 20:08:59.182744 | 2016-05-10 20:08:59.182744 | myemail@gmail.com

在使用Google登录并调用上述方法后,将创建具有相同数据的第二行。有谁知道我可以做些什么来调整一些事情,如果我的数据库中已经有一行用户,调用上面的方法将不会创建第二个重复的用户。

谢谢, - 戴夫

编辑:以下是通过Google OAuth登录后数据库的外观

 id |   provider    |          uid          |     name      |                                 oauth_token                                 |  oauth_expires_at   |         created_at         |         updated_at         |          email          
----+---------------+-----------------------+---------------+-----------------------------------------------------------------------------+---------------------+----------------------------+----------------------------+-------------------------
  5 | google-oauth2 | 777711643329020555465 | Dave A        |                                                                             |                     | 2016-05-10 20:08:59.182744 | 2016-05-10 20:08:59.182744 | myemail@gmail.com
  7 | google_oauth2 | 777711643329020555465 | D. A.         | ya29.CjLeAiJ--FTY1UhMwXdb7yk74hhdCH4O6sz3ewbG8wBNdmRHAJWZ0esoS0yZLp5fXmS60Q | 2016-05-10 21:49:55 | 2016-05-10 20:49:57.277341 | 2016-05-10 20:49:57.277341 | myemail@gmail.com

1 个答案:

答案 0 :(得分:1)

您不应该使用savefirst_or_create会在找不到匹配项时为您保存,请参阅http://apidock.com/rails/ActiveRecord/Relation/first_or_create

所以只需删除它: user.save!