1

在示例登录程序中,我有两个类。会话和用户。用户表有两个字段名,密码。调用用户类的身份验证方法时,会话方法继续获取“NoMethodError”。

用户类如下所示:

class UserController < ApplicationController
  def index
    @user = User.find(:first, :order => 'RANDOM()')
  end

  def show
   @user = User.find(:all)
  end

  def new
    @user = User.new
   #redirect_to user_path
  end

  def create
    @user = User.new(params[:user])
    @user.save
    #redirect_to 'http://localhost:3000/user/show'
  end


  def self.authenticate( password)
    #user = User.find_by_name(name)

    if user.find_by_password(password)#match_password(password)
      return true
    else
      return false
    end
  end

 def self.match_password(password="")
   encrypted_password == BCrypt::Engine.hash_secret(password, salt)
 end  
end

session 类有 create 方法,该方法调用用户的 authenticate fn。这是创建方法

def create
   user = User.find_by_name(params[:session][:name].downcase)

   if user && user.authenticate(params[:session][:password])
     # Sign the user in and redirect to the user's show page.
     sign_in user
     redirect_to user
   else
     flash.now[:error] = 'Invalid email/password combination' # Not quite right!
     render 'new'
   end
end

这是堆栈

Started POST "/sessions" for 127.0.0.1 at Sun Sep 30 15:21:02 -0400 2012
Processing by SessionsController#create as HTML
  Parameters: {"commit"=>"Sign in", "session"=>{"name"=>"ar", "password"=>"[FILTERED]"}, "authenticity_token"=>"vxYHw/4JV2fJuvvBN4GVLv31aBl8ETEtQPBB/483q/Q=", "utf8"=>"✓"}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."name" = 'ar' LIMIT 1
Completed 500 Internal Server Error in 4ms

NoMethodError (undefined method `authenticate' for #<User:0xb69650e4>):
  app/controllers/sessions_controller.rb:10:in `create'

提前致谢,A。

4

1 回答 1

0

这个块应该在你的用户模型中而不是在 UserController 中:

def self.authenticate( password)
  #user = User.find_by_name(name)

  if user.find_by_password(password)#match_password(password)
    return true
  else
    return false
  end
end

原因是您想调用.authenticateUser 对象的实例,这是在模型中发生的事情。

控制器中的函数通常用于处理请求,例如响应访问您应用程序上的 URL 的人/users/123/authenticate(在这种情况下,这不是您想要的)。

于 2012-10-09T07:45:31.353 回答