Rails 4验证方法未定义

时间:2014-02-03 15:38:08

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我在Apress上购买了“Beginning 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 %>

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你可能错过了bcrypt-ruby gem。

将此添加到您的Gemfile:

gem 'bcrypt-ruby'

在您的用户模型中,您需要添加:

class User < ActiveRecord::Base
  has_secure_password
  ...
end

确保迁移rake db:migrate并重启服务器

答案 1 :(得分:1)

尝试创建方法:

class SessionsController < ApplicationController
  def create
    user = User.where(email: params[:email]).first
    if user && user.authenticate(params[:password])

...

注意:authenticate适用于实例变量。