在示例登录程序中,我有两个类。会话和用户。用户表有两个字段名称,密码。在调用用户类的authenticate方法时,sessions方法继续获得“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
sessions类有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'
先谢谢, 甲
答案 0 :(得分:0)
此块应位于User模型中,而不是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
原因是您想要在User对象的实例上调用.authenticate
,这是模型中发生的事情。
控制器中的功能通常用于提供请求,例如,响应有人访问您应用中的网址/users/123/authenticate
(在这种情况下,这不是您想要的)。