gpt4 book ai didi

ruby-on-rails - 验证失败 : Password can't be blank

转载 作者:行者123 更新时间:2023-12-02 06:16:31 25 4
gpt4 key购买 nike

我有一个基于 Rails 4.2 构建的应用程序,并尝试使用 RailsCasts #241 Simple OmniAuth 进行 Twitter 身份验证。
但是有这个问题: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

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

最佳答案

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

关于ruby-on-rails - 验证失败 : Password can't be blank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29138323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com