Richlewis
Richlewis

Reputation: 15374

Default Route for an admin User (Devise)

Little issue here, I cant seem to route an admin user to the appropriate place. I have setup devise and added the column admin and set it as boolean. I have then updated my user to admin => true and verified this in the console.

When i log into my app a user is routed to one page and the admin user should be routed to another, here is what i have so far

  authenticated :current_admin_user do
  root :to => 'book#searchbook'
  end

  authenticated :user do
   root :to => 'search#index'
  end

  root :to => 'main#index'

However when i log in as thew admin user I get routed to 'search#index' as if i was a regular user.. What do i need to do to get the admin user routed to 'book#searchbook'. Ive never had a problem with this before

Any help appreciated

EDIT

ok so after some more research i need to specify the after_sign_in_path for an admin user, so far i have this

def after_sign_in_path_for(resource)
  if current_admin_user
searchbook_path
  else
root_path
end
end

but still it directs me to the user login page

Thanks

Upvotes: 1

Views: 621

Answers (2)

UserROR
UserROR

Reputation: 240

Just try to implement the below code .. As I used this code in my controller..

def after_sign_in_path_for(resource_or_scope)
  if resource_or_scope.is_a?(User)
     return root_path
  else
    return search_path
  end
end

Upvotes: 0

Richlewis
Richlewis

Reputation: 15374

Ok so it seems as if I had quite a bit missing, so if anyone else has had problems like this before here's what i done

In the User model i added

def is_admin?
 self.admin == 1
end

and then in my application controller i added these methods

  def authenticate_admin_user!
  authenticate_user!
    unless current_user.admin?
    flash[:alert] = "This area is restricted to administrators only."
    redirect_to root_path
  end
 end

def current_admin_user
  return nil if user_signed_in? && !current_user.admin?
  current_user
end

def after_sign_in_path_for(resource)
if current_user.admin?
searchbook_path

else
 root_path
end
end

and then in the controller that was only accessible by the admin user I added before_filter

before_filter :authenticate_admin_user!

Hope this helps anyone else in same situation (and thanks to Jayson Lane)

Turns out he helped me 9 months ago with the same issue...

Upvotes: 2

Related Questions