0

I have a method which can create a user from facebook user accounts. I validate email column to make sure it is unique.

class User < ActiveRecord::Base
  validates :email,
    :'validators/email' => true,
    allow_nil: true,
    uniqueness:{ case_sensitive: false }

Sometimes in production, a FB user is unable to create an account. It says the email of the user already exists in the database. So I wrote some code to get existing user if this happens.

  def self.create_by_facebook()
    user = User.new()
    user.email = facebook_get_me()['email']

    # new code
    if user.invalid?
      if user.errors[:email].join.include?('already registered') #custom msg
        user = User.find_by_email(user.email)
        if user.nil?
          FacebookLogger.error("  no user is found by facebook email")
        end
      end
    end

    begin
      user.save!
    rescue ActiveRecord::RecordInvalid => e
      raise
    end

    user
  end

However, this time the error is undefined methodsave!' for nil:NilClass`. Since the validation says the email already exists, my finder should return that one existing user record, but now it returns nil. How can this occur?

For the record I have logged down the error, and the email is a proper email address. This happens about once a day, and I can't reproduce it myself.

lulalala
  • 17,572
  • 15
  • 110
  • 169

1 Answers1

0

might be this line cause issue because if user is not found it will return nil,you are not raising exception ,you are logging the exception,

user = User.find_by_email(user.email)

Your code is much complicated you can write simple code to achieve above result.

Amar
  • 6,874
  • 4
  • 25
  • 23
  • Yes I know it is this line, but my question is why it can return nil when `invalid?` is saying that email already exists in the database. – lulalala Sep 11 '12 at 10:14
  • can you inspect user object above begin block try to put debugger or pry,what it's returning? – Amar Sep 11 '12 at 10:25
  • use `user1 = User.find_by_email(user.email)` and `if user1.nil?` – Amar Sep 11 '12 at 10:33