验证失败:密码不能为空

Igo*_*cha 2 ruby-on-rails omniauth ruby-on-rails-4.2 omniauth-twitter

我有一个应用程序,基于Rails 4.2,并尝试使用Twitter进行身份验证RailsCasts #241 Simple OmniAuth.
但是有这个问题: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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

的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'
Run Code Online (Sandbox Code Playgroud)

解决方案
编辑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
Run Code Online (Sandbox Code Playgroud)

Son*_*ute 5

我觉得这有问题

has_secure_password 
Run Code Online (Sandbox Code Playgroud)

尝试评论它,你可以覆盖has_secure_password

has_secure_password(validations: false)
Run Code Online (Sandbox Code Playgroud)

这是在它自动添加时发生的

validates_presence_of :password_digest 
Run Code Online (Sandbox Code Playgroud)

因此,当指定allow_blank或allow_null时,它将无法工作


Reg*_*ieB 5

另一种方法是在创建用户时输入随机密码。例如,如omn​​iauth-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
Run Code Online (Sandbox Code Playgroud)