在以下代码中,如果 params[:email] 包含 @ 字符,则以下行 user = User.authenticate(params[:email], params[:password]) 得到“参数数量错误(0 表示 2)”。没有 @ 字符一切正常,我不知道如何解决它。
我尝试将电子邮件作为字符串发送,例如 user = User.authenticate("test@test.com", params[:password]) ,但没有收到错误消息。
有人可以帮忙吗?
我的代码:
控制器:
class SessionsController < ApplicationController
def new
end
def create
user = User.authenticate(params[:email], params[:password])
if user
session[:user_id] = user.id
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
end
模型:
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret ↵
(password, user.password_salt)
user
else
nil
end
end
结尾