I have the following action:
users.rb:
def omniauth_create
auth = request.env["omniauth.auth"]
user = User.from_omniauth(env["omniauth.auth"])
unless user.email.blank?
if user.id.nil?
# Save the user since he hasn't been created yet
user.save!
end
sign_in user
redirect_back_or user
else
# Send user to a form to fill his email
#session[:omniauth] = request.env['omniauth.auth'].except('extra')
redirect_to(enter_email_path(oprovider: user.provider,
ouid: user.uid,
oname: user.name,
opassword: user.password,
opassword_confirmation: user.password))
end
end
It does the following:
- If the user’s
emailis not blank, sign him in, and redirect him to his profile (and save him if hisidisnil. In other words, if he hasn’t been created yet). - If the user’s
emailis blank, send him toenter_email_path(where the user can enter his email).
Now I want to add another if statement that flashes an error if the email had been already taken, and redirects the user to the root_path
I’m not very sure how to do this, Any suggestions? (and where to put that if statement?)
EDIT:
Strange, got this instead of the redirect to the root path:
Validation failed: Email has already been taken
I don’t know if this helps but here is the origin of from_omniauth:
def self.from_omniauth(auth)
find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
end
def self.create_with_omniauth(auth)
new do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
user.email = auth["info"]["email"]
user.password = user.password_confirmation = SecureRandom.urlsafe_base64(n=6)
end
end
The code as it is right now:
user.rb:
# if user.email.present?
if user.id.nil?
# User.find_by_email(user.email).present?
if User.exists?(:email => user.email)
redirect_to root_path
end
user.save!
end
sign_in user
redirect_back_or user
else
(the rest didn’t change).
It seems like the code is ignoring the if User.exists?(:email => user.email) part?
Rails has a method to check if an object
existsbased on parameters. You could do this:By the way, I am not familiar with Omniauth so I am not sure what is right but
new_record?is usually used when checking if object is already saved or not. If you have anid, it usually is.If you are confused you could create functions in your User model for better reading like