2

我有一个应用程序,基于 Rails 4.2 构建并尝试使用RailsCasts #241 Simple OmniAuth.
但是有这个问题:Validation failed: Password can't be blank!
我到处搜索答案,但没有找到解决方案!

用户.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

session_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

路线.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
4

2 回答 2

5

另一种方法是在创建用户时输入随机密码。例如,如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
于 2015-03-19T07:54:12.220 回答
5

我认为这是问题

has_secure_password 

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

has_secure_password(validations: false)

这种情况正在发生,因为它会自动添加

validates_presence_of :password_digest 

因此,当指定 allow_blank 或 allow_null 时,它将不起作用

于 2015-03-19T06:52:28.757 回答