问题
I am loosely following Railscasts Simple OmniAuth http://railscasts.com/episodes/241-simple-omniauth to create my Twitter login. When I try to sign in and create a new user through twitter, I get the following message:
Validation failed: Password can't be blank, Name is not valid., Email can't be blank, Email is not valid.
If I hit the refresh button, I get the following error:
OAuth::Unauthorized 401 Unauthorized
I've already set my callback URL to http://127.0.0.1:3000/auth/twitter/callback
but I still get that message. I'm testing on localhost.
I modeled my users after Hartl's railstutorial http://ruby.railstutorial.org/ruby-on-rails-tutorial-book and my website project requires that users have those fields filled in.
Unlike the railscasts, I created a new method to handle omniauth logins:
sessions_controller.rb
def omniauth_create
auth = request.env["omniauth.auth"]
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
user.rb
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
end
end
Question: How do I bypass the validations?
So far, I've tried using skip_before_filter :authenticate, :only => [:omniauth_create]
, but that didn't work.
Thanks.
回答1:
There are two ways to skip the validations. Either you can skip them all by passing :validate => false
to the create method (usually A Bad Idea), or you can modify your validations to something like the following:
user.rb
validates_confirmation_of :password, :if => :password_required?
def password_required?
!provider.blank? && super
end
来源:https://stackoverflow.com/questions/10728005/simple-omniauth-twitter-failing-to-create-new-user-because-of-validation