Monday, July 11, 2016

Devise: redirect to specific pages after sign in using different models

As you should know, Devise can be applied in the same project to different models, but I couldn't find a simple way to redirect users after signing in, based on the kind of resource they were representing (e.g. let's say users and vendors).

After searching for long how to solve this issue and finding long and winding solutions, I found a way to solve it myself in a very simple way; as it is here it's really bare bones and possibly prone to bugs, but it does exactly what I wanted, so I thought other people might find it interesting.

So, let's say we are using Devise on the user and vendor models, and we generated our custom session controllers in user/sessions_controller.rb and vendor/sessions_controller.rb. The first thing that came to my mind was to find a way to customize the redirection from the controllers by overwriting some of the functions, but it turned out to be complicated and not working as expected.

As such I came out with a much simpler even though less elegant solution; that is overwriting the default function after_sign_in_path_for(resource) in the application controller, checking whether in my session I have an instance of one kind of resource or the other.

Here is the relevant code:

class ApplicationController < ActionController::Base
  
  [...]

  def after_sign_in_path_for(resource)
    if current_user
      "your_user_url"
    elsif current_vendor
      "your_vendor_url"
    end
  end
end

I hope this will help you as much as it helped me.

No comments: