简体   繁体   中英

devise: is it possible to sign in user in the model?

My app creates a user in a callback of a model and I can't figure out how to seamlessly sign him in after that, as sign_in helper is available only in the controller.

after_validation do
  return unless errors.empty?
  if create_account == "1"
    begin
      self.user ||= User.create!(...)
  rescue => e
    errors.add(:create_account, 'bla bla')
  end
end

end

So how to sign in user after it has been created (in the model)?

You can not sign in a user through the model and you don't want to do that either.

Why are you using a validation callback here?

If you move part of this logic to your controller you can easily achieve what you want.

def MyController < ApplicationController
  def my_action
    my_instance.user ||= User.new(...)
    if my_instance.user.save
      sign_in my_instance.user
    end
  end
end

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