Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 + Devise: sign_in(user) method not working, does not set current_user

I'm working on a checkout for a store. When the form is submitted, this action takes place in my controller

def update_billing
  ...
  if @checkout.save
    sign_in(guest_user) #<--
    redirect_to root_path, notice: "Success!"
  else
    render 'billing'
  end
end

I test this by raiseing inside the action and testing it out using better_errors:

    >> sign_in(guest_user) if params[:checkout_form][:create_an_account] == "1"
    => #<User id: 8, email: "[email protected]", encrypted_password: "$2a$10$HCv7veSO7LC9Dh1tKD0Jbe57Pz6lAsiZgfIiWOys7bF...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 6, current_sign_in_at: "2014-06-04 19:45:36", last_sign_in_at: "2014-06-04 19:29:48", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-04 18:50:29", updated_at: "2014-06-04 19:45:36", guest: false, guest_email: "[email protected]">
    >> current_user
    => #<User id: 8, email: "[email protected]", encrypted_password: "$2a$10$HCv7veSO7LC9Dh1tKD0Jbe57Pz6lAsiZgfIiWOys7bF...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 6, current_sign_in_at: "2014-06-04 19:45:36", last_sign_in_at: "2014-06-04 19:29:48", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-04 18:50:29", updated_at: "2014-06-04 19:45:36", guest: false, guest_email: "[email protected]">

    >> session["warden.user.user.key"]
    => [[8], "$2a$10$HCv7veSO7LC9Dh1tKD0Jbe"]

However, when I go back to localhost:3000/ , current_user becomes nil again:

    >> session["warden.user.user.key"]
    => nil
    >> current_user
    => nil

Doesn't sign_in(guest) user set the session variables so that current_user will "persist" across requests?

What am I doing wrong?

like image 372
bigpotato Avatar asked Jun 04 '14 19:06

bigpotato


1 Answers

I figured it out. In my @checkout form object, I update the guest_users attributes and save it when I call @checkout.save. I think devise has to sign in the most recent version of guest_user, so I had to add a guest_user.reload before sign_in(guest_user)

In short, reload your user (user.reload) before signing it in.

like image 88
bigpotato Avatar answered Sep 18 '22 14:09

bigpotato