简体   繁体   中英

Rails, Devise: current_user is nil when overriding RegistrationsController

Rails 3.2.5, Devise 2.1

Using Devise to authenticate Users, and am having a problem when creating a new user.

A user belongs to an Account which I create using a before_save filter in the User model. This works fine and has for a while.

New code requires the user's account information as part of the create method. I rely on a parameter passed in the request, so this is not a good candidate for Model logic. I have overridden the Devise::RegistrationsController#create method:

class DeviseCustom::RegistrationsController < Devise::RegistrationsController
  def create
    super                                  # Call Devise's create
    account = current_user.account         # FAIL! (current_user is nil)
    account.partner_id = current_partner
    account.save!
  end
end

current_user is nil which causes the code to fail. Even in the case of a failure, I can see that the user and account records are being saved in the database -- the logs show the commit , and logging self.inspect shows all my context (params, and much more) is all still present.

I would have thought that current_user would be available in this context -- what's an appropriate way to get at the user I have just created?

Thanks

通过在覆盖时将它们包括在控制器中,我能够使用Devise帮助器方法。

include Devise::Controllers::Helpers

: I've never used devise. :我从没用过设计。

My guess is the current_user object hasn't been created, either because there wasn't a reason to (no user credentials) earlier on in the call chain, or because it hasn't yet happend perhaps in #after_save (if that exists?).

Devise uses a #resource method to grab the current instance variable you're trying to save (or so it looks):

https://github.com/plataformatec/devise/blob/master/app/controllers/devise_controller.rb#L16

What I would do is change the it to:

class DeviseCustom::RegistrationsController < Devise::RegistrationsController
    def create
      super                                  # Call Devise's create
      account = resource.account         # FAIL! (current_user is nil)
      account.partner_id = resource.current_partner
      account.save!
    end
end

You'll probably want to add this to your model:

attr_accessor :current_partner

which will allow you to access the current_partner from the resource (model).

Hopefully that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM