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

ruby-on-rails

Solution

I figured it out. In my `@checkout` form object, I update the `guest_user`s 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.

Problem

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 `raise`ing 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: "abc123@yahoo.com", 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: "guest_140190782975@example.com"> >> current_user => #<User id: 8, email: "abc123@yahoo.com", 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: "guest_140190782975@example.com"> >> 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?

Original source