我有一个应用程序,建立在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
尝试'allow_blank'取代'allow_nil' – Sontya 2015-03-19 06:26:49
它什么都没有改变! – 2015-03-19 06:28:07
现在就放弃'minimum'验证,只需尝试'allow_blank' – Sontya 2015-03-19 06:32:33