Rails 4 + Devise:sign_in(用户)方法不起作用,不设置current_user

big*_*ato 10 ruby-on-rails

我正在办理商店结账.提交表单时,此操作将在我的控制器中进行

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

我通过raise操作内部测试并使用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"]
Run Code Online (Sandbox Code Playgroud)

但是,当我回到localhost:3000 /时,再次current_user成为nil:

    >> session["warden.user.user.key"]
    => nil
    >> current_user
    => nil
Run Code Online (Sandbox Code Playgroud)

sign_in(guest)用户是否设置会话变量以便current_user跨请求"持久"?

我究竟做错了什么?

big*_*ato 5

我想到了。在我的@checkout表单对象中,我更新guest_users 属性并在调用 时保存它@checkout.save。我认为 devise 必须登录最新版本的 guest_user,所以我必须guest_user.reload在之前添加一个sign_in(guest_user)

简而言之,user.reload在登录之前重新加载您的用户 ( )。