vfilby vfilby - 6 months ago 46
Ruby Question

Can I execute custom actions after successful sign in with Devise?

I have an app that has basic Devise authentication. After sign in, I would like to look up the user account (user belongs_to account, account has_many users), and store that in the session so that it is available like the

@current_user
.

What is the rails way of storing session in formation like this?
Is there a hook I can use with Devise to execute code after successful sign-in?

Answer

Edit: Please consider that this was once a good solution, but there are probably better ways of handling this. I am only leaving it here to give people another option and to preserve history, please do not downvote.

Yes, you can do this. The first resource I'd look at is http://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in. Also, check out How to redirect to a specific page on successful sign up using rails devise gem? for some ideas.

You can do something like:

def after_sign_in_path_for(resource_or_scope)
  session[:my_account] = current_user.account
  profile_url
end

You can implement this method in your ApplicationController or in a custom RegistrationsController.