我创建了一个方法" attempt_login"如下所示:
def attempt_login
if params[:username].present? && params[:password].present?
found_user= AdminUser.where(:username=> params[:username].first)
if found_user
authorized_user= found_user.authenticate(params[:password])
end
end
if authorized_user
flash[:notice]="You are now logged in."
redirect_to(:action=>'menu')
else
flash[:notice]="Invalid username/password combination."
redirect_to(:action=>'login')
end
end
我收到这样的错误:
←[1m←[35mAdminUser Load (1.0ms)←[0m SELECT `admin_users`.* FROM `admin_users`
WHERE `admin_users`.`username` = 'u'
Completed 500 Internal Server Error in 18ms
NoMethodError (undefined method `authenticate' for #<ActiveRecord::Relation []>)
:
app/controllers/access_controller.rb:13:in `attempt_login'
它可以从rails控制台运行,但不能从rails服务器运行。 请告诉我解决方案,我在等你的回复。
答案 0 :(得分:1)
你的代码中有错,这个:
found_user = AdminUser.where(:username => params[:username].first)
应该是:
found_user = AdminUser.where(:username => params[:username]).first
查看日志:
SELECT `admin_users`.* FROM `admin_users`
WHERE `admin_users`.`username` = 'u'
params[:username].first
返回params[:username]
中的第一个字符,但您需要先记录:
AdminUser.where(:username=> params[:username]).first
答案 1 :(得分:1)
您可以使用find_by
。
Rails 3:
AdminUser.find_by_username(params[:username])
Rails 4:
AdminUser.find_by(username: params[:username])