Question

I would like to test for multiple roles using rolify.

I tried this and it didn't work:

<% if current_user.has_role? [:technician, :admin] %>

Thanks for the help!

UPDATE1

I'm trying to test for :technician or :admin - this works but seems like there should be a shorter way:

if current_user.has_role? :technician or current_user.has_role? :admin
Was it helpful?

Solution 2

Look at the Rolify docs:

Multiple role checking Check if the user has ALL specified roles

  user = User.find(1)
  user.add_role :admin # sets a global role
  user.add_role :moderator, Forum.first # sets a role scoped to a resource instance
  user.add_role :visitor, Forum # sets a role scoped to a resource class
  user.has_all_roles? :admin, { :name => :moderator, :resource => Forum.first }, { :name => :visitor, :resource => Forum }
  => true
  user.has_all_roles? :admin, { :name => :moderator, :resource => Forum.last }
  => false
  user.has_all_roles? :god, { :name => :visitor, :resource => Forum }
  => false

Check if the user has ANY of the specified role(s)

  user = User.find(1)
  user.add_role :admin # sets a global role
  user.add_role :moderator, Forum.first # sets a role scoped to a resource
  user.add_role :visitor, Forum # set a role scoped to a resource class
  user.has_any_role? :admin, { :name => :moderator, :resource => Forum.first }, { :name => :visitor, :resource => Forum }
  => true
  user.has_any_role? :admin, { :name => :moderator, :resource => Forum.last }
  => true
  user.has_any_role? :god, { :name => :visitor, :resource => Forum }
  => true

So it looks like in your situation you want to use:

user.has_all_roles? :technician, {:name => :admin}

OTHER TIPS

I'd recommend you test something like current_user.has_any_role? :technician, :admin, it should return you the boolean you're expecting :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top