2

会话控制器:

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用户模型来提供的?我在这里错了吗?

任何帮助表示赞赏!

4

1 回答 1

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
于 2013-08-23T07:03:18.437 回答