1
votes

Experiencing a very strange bug with rails 4.1.3 and devise 3.0.4. Trying to handle anonymous logins. Either the user is logged in through devise or he has filled in name and email in a previous form.

Following code in the controller:

   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}"

Following log output:

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: "[email protected]", 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

So this is what I don't get, why is the current_user object being reset to nil even though the code in the if block is not being executed...

What's going on?

Thanks in advance - Mike

1

1 Answers

1
votes

You need to do

sign_in(current_user)

like this:

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}"

or set the instance variable:

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}"