会话控制器:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && User.authenticate(params[:password])
session[:user_id] = user.id
redirect_to products_path, notice: 'Logged in successfully'
else
flash.now.alert = "Email or password is invalid"
render 'new'
end
end
def destroy
end
end
用户模型:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :password, :password_confirmation
validates_uniqueness_of :email
end
登录表单:
<h1>Login form</h1>
<%= form_tag sessions_path do %>
<%= label_tag :email %><br/>
<%= text_field_tag :email, params[:email] %><br/>
<%= label_tag :password %><br/>
<%= password_field_tag :password, params[:password] %><br/>
<%= submit_tag "Login" %>
<% end %>
当我尝试使用我的登录表单时,会引发NoMethodError,指出authenticate
未定义。
我认为通过将has_secure_password
放在用户模型中来提供身份验证方法?我错了吗?
任何帮助表示赞赏!
答案 0 :(得分:3)
我相信您需要对用户对象进行身份验证,请尝试使用此
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to products_path, notice: 'Logged in successfully'
else
flash.now.alert = "Email or password is invalid"
render 'new'
end
end