我已经坚持了几个小时的奇怪问题:
我正在使用 Rails 3 编写一个简单的用户登录,其中用户使用他们的电子邮件和密码登录。在我的用户模型中,我试图通过他们的电子邮件找到正确的用户对象,然后继续查看他们是否输入了正确的密码。
当我尝试从 rails 控制台查找用户时
>> User.find_by_email("test@email.com")
我得到了想要的结果——返回了正确的用户对象
User Load (0.7ms) SELECT `users`.* FROM `users` WHERE `users`.`email` = 'test@email.com' LIMIT 1
=> #<User id: 21, first_name: "Test", last_name: "Man", hashed_password: "ca630762c6dce11af5a9923c7955131f8d6f7a16", cell_phone_number: nil, email: "test@email.com", created_at: "2012-12-13 14:35:38", updated_at: "2012-12-13 14:35:38", salt: nil, is_admin: false>
但是当我将以下代码放入 model/user.rb 文件时,我得到了一个奇怪的结果
user = User.find_by_email("test@email.com")
puts "******** user = #{user}"
输出以下内容:
******** user = #<User:0x10b7b82c8>
当我尝试使用这个用户变量时,它会出错并说变量或方法“用户”是未知的
这是日志文件的输出:
Started POST "/users/login_attempt" for 127.0.0.1 at Thu Dec 13 08:40:47 -0600 2012
Processing by UsersController#login_attempt as HTML
Parameters: {"password"=>"[FILTERED]", "utf8"=>"", "email"=>"asdf", "authenticity_token"=>"4xeLxpSb4GidsHUIe4b55LhOVJtDEiv5UaQYU9aBv5k=", "commit"=>"Log In"}
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`email` = 'test@email.com' LIMIT 1
这是我尝试过的一些事情......
上面的mysql查询肯定有效。我已经将它复制到 mysql 中,它得到了正确的用户。
我试过 find(id) 也不起作用。返回类似的用户:0x10b7b82c8
总的来说,我不明白为什么控制台会给出与模型代码本身不同的结果。
有人知道为什么我会从 find_by 得到如此奇怪的结果吗?
非常感谢!
编辑:这是附加代码,因为 Frederick 提到不足以找到问题。
来自控制器/users_controller.rb
class UsersController < ApplicationController
def login
end
def login_attempt
authorized_user = User.authenticate(params[:email], params[:password])
redirect_to({:controller => 'records', :action => 'list'} )
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
redirect_to({:controller => 'records', :action => 'list'} )
else
render('new')
end
end
end
来自模型/user.rb
require 'digest/sha1'
class User < ActiveRecord::Base
attr_accessible :password, :password_confirmation, :email, :email_confirmation, :first_name, :last_name
attr_accessor :password
before_save :create_hashed_password
after_save :clear_password
# only on create, so other attributes of this user can be changed
#create method to authenticate login credentials
def self.authenticate(email,password)
user = User.find_by_email("test@email.com")
puts "******** user = #{user}"
end
#method to check provided password against password stored in db
def password_match?(password="")
newuser.hashed_password == hash_password(password)
end
#hash_password adds salt to password and encrypts it
def self.hash_password(password="")
salted_pw = password + PW_SALT
hashed_pw = Digest::SHA1.hexdigest(salted_pw)
end
private
def create_hashed_password
# Whenever :password has a value hashing is needed
unless password.blank?
# self.hashed_password = User.hash_password(password)
self.hashed_password = User.hash_password(password)
end
end
def clear_password
# for security and b/c hashing is not needed
self.password = nil
end
end