I’m trying to set up Omniauth login for Twitter/FB. I created my own authentication system that validates for password and email upon creation of a user. However, I do not want to validate for password or email when my users log in through Twitter/Fb.
I created a user attribute called omniauth_login. I am using it as a boolean to test whether validation is required or not in my should_validate_password? method.
User.rb
attr_accessor :password, :updating_password, :omniauth_login
validates_presence_of :password, :if => :should_validate_password?
validates_confirmation_of :password, :if => :should_validate_password?
def should_validate_password?
(updating_password || new_record?) && !(self.omniauth_login == 'true')
end
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
end
end
Here is my controller used to create the user:
sessions_controller.rb
def omniauth_create
auth = request.env["omniauth.auth"]
user = User.new
user.omniauth_login = 'true'
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) ||
User.create_with_omniauth(auth)
session[:user_id] = user.id
redirect_to user
end
When I try to create a new user by logging in via twitter, I still get the validation error:
Validation failed: Password can't be blank, Email can't be blank, Email is not valid.
How do I skip validation of password and email if my object is being created in the create_with_omniauth method?
Thanks.
I think the problem here is that you have two separate instances of User, one that has omniauth_login set to ‘true’, and another that does not. The first is gotten from
The second is
. The second instance created here doesn’t have omniauth_login set to ‘true’, so it still runs the validations. Try this instead
and in create_with_omniauth, add
user.omniauth_login = 'true'.