current_user在rails / devise中设置为nil

时间:2014-10-30 13:37:24

标签: ruby-on-rails devise

使用rails 4.1.3遇到一个非常奇怪的错误并设计3.0.4。试图处理匿名登录。用户通过设计登录,或者他已填写以前表格中的姓名和电子邮件。

跟随控制器中的代码:

   logger.debug "current_user before:#{current_user.inspect}"
   if(current_user.nil?)
     current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email])
     logger.debug "Guest user created" 
   end
   logger.debug "current_user after:#{current_user.inspect}"

跟踪日志输出:

D, [2014-10-30T14:10:15.627130 #2148] DEBUG -- : current_user before:#<User _id: 52ffe1b35043001fa8000000, created_at: 2014-02-15 21:52:51 UTC, updated_at: 2014-10-30 13:00:47 UTC, email: "xxx@yyy.com", encrypted_password: "$2a$10$r5wXs97N.HIAp9bp5GZBaOUt8R5.S/Z/2PhcpF0xaIVuTD4BpZrmO", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 134, current_sign_in_at: 2014-10-30 13:00:47 UTC, last_sign_in_at: 2014-10-30 12:57:35 UTC, current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: 2014-02-15 21:53:04 UTC, confirmation_sent_at: 2014-02-15 21:52:51 UTC, unconfirmed_email: nil, image: "", first_name: "Dave", last_name: "Something", roles_mask: 7>
D, [2014-10-30T14:10:15.629130 #2148] DEBUG -- : current_user after:nil

所以这就是我没有得到的,为什么current_user对象被重置为nil,即使if块中的代码没有被执行...

发生了什么事?

提前致谢 - 迈克

1 个答案:

答案 0 :(得分:1)

你需要做

sign_in(current_user)
像这样:

if(current_user.nil?)
  current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email])
  sign_in(current_user)
  logger.debug "Guest user created" 
end
logger.debug "current_user after:#{current_user.inspect}"

或设置实例变量:

if(current_user.nil?)
  @current_user = User.create(:last_name => params[:guest_username], :email => params[:guest_email])
  logger.debug "Guest user created" 
end
logger.debug "current_user after:#{current_user.inspect}"