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
Preface: 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:
You’ll probably want to add this to your model:
which will allow you to access the current_partner from the resource (model).
Hopefully that helps!