简体   繁体   中英

unique after_sign_out paths with multiple models with Devise and rails

I have a rails 3.2 app with Devise 2.1

I have 2 models using devise (AdminUser and User)

Models:

class AdminUser < ActiveRecord::Base
    devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable
end

class User < ActiveRecord::Base
    devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
end

I have generated separate views for both models via the devise generator. views/devise folder for AdminUser (implemented months earlier before new requirement) views/users folder for User model

After signout, I want to redirect to specific actions that match the devise models. The code below works in application_controller.rb but it is applying to both models which I want to do without:

def after_sign_out_path_for(user)
  user_landing_path
end

Signing out of either model redirects to the same landing page, but i would like to have a unique destination for both devise models.

How can I achieve this?

I figured out what seems to be a solution after looking at some examples here http://eureka.ykyuen.info/2011/03/10/rails-redirect-previous-page-after-devise-sign-in/

def after_sign_out_path_for(resource_or_scope)
  case resource_or_scope
    when :user, User
      user_landing_path
    when :admin_user, AdminUser
      admin_user_landing_path
    else
      super
  end
end

Some things you could do:

case user.class
when AdminUser.class
  do_admin_sign_out()
when User.class
  do_user_sign_out()
else
  no_idea_who_you_are()
end

or

if user.kind_of? AdminUser
  do_admin_thing()
else
  do_user_thing()
end

alternatively, you could add an admin? check to both models, and check that, ie:

if user.admin?
  do_admin_thing()
...

I would probably do the later, as this might come up else where, but these are among your options.

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