2015-03-19 110 views
2

我有一个应用程序,建立在Rails 4.2上,并尝试使用RailsCasts #241 Simple OmniAuth进行twitter身份验证。
但有这个问题:Validation failed: Password can't be blank!
我到处搜索答案,但没有找到解决方案!验证失败:密码不能为空

user.rb

class User < ActiveRecord::Base 

    has_secure_password 
    validates :password, length: { minimum: 6 }, allow_blank: true 
    def self.create_with_omniauth(auth) 
     create! do |user| 
      user.provider = auth.provider 
      user.uid = auth.uid 
      user.name = auth.info.name 
     end 
    end 
end 

sessions_controller.rb

class SessionsController < ApplicationController 
    def login 
    end 

    def create 
     @user = User.find_by_email(params[:email]) 
     if @user && @user.authenticate(params[:password]) 
      session[:user_id] = @user.id 
      redirect_to root_path 
     else 
      redirect_to :back 
     end 
    end 

    def create_session 
     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 root_url, notice: 'Signed in!' 
    end 

    def logout 
     reset_session 
     redirect_to root_path 
    end 
end 

的routes.rb

get 'sessions/login' 
    get 'sessions/logout' 
    post 'sessions' => 'sessions#create' 

    get '/auth/:provider/callback' => 'sessions#create_session' 
    post '/auth/:provider/callback' => 'sessions#create_session' 

    get 'registration' => 'users#new', as: 'registration' 

解决方案
编辑user.rb后模型的样子:

class User < ActiveRecord::Base 

    has_secure_password 
    validates :password, length: { minimum: 6 } 
    require 'securerandom' 
    def self.create_with_omniauth(auth) 
     create! do |user| 
      user.provider = auth.provider 
      user.uid = auth.uid 
      user.name = auth.info.name 
      user.password = SecureRandom.urlsafe_base64 
     end 
    end 
end 
+0

尝试'allow_blank'取代'allow_nil' – Sontya 2015-03-19 06:26:49

+0

它什么都没有改变! – 2015-03-19 06:28:07

+0

现在就放弃'minimum'验证,只需尝试'allow_blank' – Sontya 2015-03-19 06:32:33

回答

3

另一种方法是对用户创建输入随机密码。例如,如omniauth-google-oauth2自述文件中所示。所以,你可以改变你的代码如下:

require 'securerandom' 
def self.create_with_omniauth(auth) 
    create! do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.name = auth.info.name 
     user.password = SecureRandom.urlsafe_base64 
    end 
end 
+0

似乎并没有解决底层问题,下面的解决方案似乎并不适用于我,但它现在正在工作! – 2017-11-29 16:00:26

5

我认为这是与

has_secure_password 

问题尽量评论它,你可以重写has_secure_password或者

has_secure_password(validations: false) 

这是自动发生的LLY增加

validates_presence_of :password_digest 

因此,当指定allow_blank或allow_null它不会工作