Rails7手动实现用户登录系统时BCrypt::Engine cost方法未定义如何解决
修复方案
错误根源
undefined method 'cost' for BCrypt::Engine:Class报错由User模型中错误引入BCrypt模块导致,和Rails内置has_secure_password的BCrypt调用逻辑产生命名冲突。
具体修改步骤
1. 修正User模型代码
删除require 'bcrypt'、include BCrypt两行代码,同时删除模型中多余的user_params方法(该方法属于控制器层逻辑,无需定义在模型中)。修改后代码如下:
class User < ApplicationRecord validates :email, uniqueness: true has_secure_password end
2. 修正会话控制器代码
SessionsController的create方法中存在变量名错误,将session[:user_id] = user.id修改为session[:user_id] = @user.id,同时修正拼写错误的passwrod为password。修改后代码如下:
class SessionsController < ApplicationController def create @user = User.find_by_email(params[:email]) if @user && @user.authenticate(params[:password]) session[:user_id] = @user.id redirect_to root_url, notice: "logged in!" else flash.now.alert = "Email or password is invalid" render "new" end end def destroy session.delete(:user_id) @current_user = nil end end
3. 可选适配检查
如果修改后仍有异常,可检查Gemfile中bcrypt版本,Rails 7适配的稳定版本为gem 'bcrypt', '~> 3.1.7',修改后执行bundle install重启服务即可。
内容的提问来源于stack exchange,提问作者enfloo
相关产品推荐
相关产品推荐

