为什么可以';我不能通过其身份验证令牌找到ActiveRecord实例吗?
我甚至试过:为什么可以';我不能通过其身份验证令牌找到ActiveRecord实例吗?,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我甚至试过: def current_user @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] end 但它只返回nil值。 请帮忙 控制器: begin @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] rescue Act
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
但它只返回nil值。
请帮忙
控制器:
begin
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
rescue ActiveRecord::RecordNotFound => e
@current_user ||= nil
end
编辑:
型号:
我想我在创建之前遇到了一个问题。它的编写方式是否正确?您似乎找不到该实例,因为您的web浏览器中不再存在cookie,因此存在冲突。因此,您应该清除浏览器的数据缓存,问题就会解决。您似乎找不到该实例,因为cookie不再存在于您的web浏览器中,因此存在冲突。因此,您应该清除浏览器的数据缓存,问题就会解决。这对我来说很有效,因为浏览器的cookie与保存到用户模型的cookie不一致:
before_create :generate_token(:auth_token)
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
对我来说,删除当前登录的用户时会出现问题。上面的代码停止任何错误。这对我来说很有效,因为浏览器的cookie和保存到用户模型的cookie不一致:
before_create :generate_token(:auth_token)
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
对我来说,删除当前登录的用户时会出现问题。上面的代码停止任何错误。那么,
cookies[:auth\u token]
设置了吗?是否有具有相应身份验证令牌的用户?在不了解cookies、请求或数据库状态的情况下,我们如何为您调试此程序?@meagar我添加了控制器部分。你能看看吗。真的被困在这里了!您能否在尝试使用def current\u user
方法之前,将cookies[:auth\u token]
的值打印到日志中?那么,您是否可以验证您的数据库中是否确实有一条用户
记录以及您记录的值?那么,cookies[:auth_token]
是否已设置?是否有具有相应身份验证令牌的用户?在不了解cookies、请求或数据库状态的情况下,我们如何为您调试此程序?@meagar我添加了控制器部分。你能看看吗。真的被困在这里了!您能否在尝试使用def current\u user
方法之前,将cookies[:auth\u token]
的值打印到日志中?然后,您是否可以验证您的数据库中是否确实有一条用户
记录以及您记录的值?
def current_user
@current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
rescue ActiveRecord::RecordNotFound => e
@current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
end
helper_method :current_user