我在apress上购买了"开始rails 4"的书,它使用 user.authenticate
进行身份验证,但是给我带来了错误。之后,我读了一份评论,说这本书主要涵盖了Rails 3.2,因此不再支持吗?
我收到以下错误:
undefined method `authenticate' for #<Class:0x007f83ece1a678>
class SessionsController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to root_path, :notice => "Logged in successfully"
else
我的sessions_controller.rb
class SessionsController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to root_path, :notice => "Logged in successfully"
else
flash.now[:alert] = "Invalid login/password combination"
render :action => 'new'
end
end
def destroy
reset_session
redirect_to root_path, :notice => "You successfully logged out"
end
end
查看
<h1>Login</h1>
<%= form_tag session_path do %>
<div class="field">
<%= label_tag :email %><br />
<%= text_field_tag :email %>
</div>
<div class="field">
<%= label_tag :password %><br />
<%= password_field_tag :password %>
</div>
<div class="actions">
<%= submit_tag 'Login' %>
</div>
<% end %>
事先感谢您的帮助。
您可能缺少bcrypt-ruby宝石。
将其添加到您的gemfile:
gem 'bcrypt-ruby'
在您的用户模型中,您需要添加:
class User < ActiveRecord::Base
has_secure_password
...
end
确保迁移rake db:migrate
并重新启动服务器
在创建方法中尝试:
class SessionsController < ApplicationController
def create
user = User.where(email: params[:email]).first
if user && user.authenticate(params[:password])
...
注意:身份验证适用于实例变量。