验证失败:密码不能为空

Validation failed: Password can't be blank

我有一个基于 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

我认为

有问题
has_secure_password 

尝试对其进行评论,您可以覆盖 has_secure_password

has_secure_password(validations: false)

这是因为它会自动添加

validates_presence_of :password_digest 

所以当指定 allow_blank 或 allow_null 时它将不起作用

另一种方法是在创建用户时输入随机密码。例如 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