Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all users with specific role using rolify

How can i get all users with specific role when using rolify? I've tried the following but it didn't help:

User.with_role :admin

I get the following error:

NoMethodError: undefined method `with_role' for #<Class:0x0000000743f9c0>

Couldn't find any way to do this.

like image 854
roman Avatar asked Jul 05 '12 17:07

roman


2 Answers

You can use the with_role method with a User class to find all users who has a role in version 3.1.0.

User.with_role :admin
like image 70
Lookchin Avatar answered Sep 18 '22 19:09

Lookchin


I'd ask the role for it's users

admins = Role.find_by_name('admin').users

the with_role method is for a particular user instance, not at the class-level for all users. If you want to implement that you'd have to do something like this:

#not 100% on this code, haven't tested it, but you get the idea.
User < ActiveRecord::Base
  def self.with_role(role)
     my_role = Role.find_by_name(role)
     where(:role => my_role)
  end
end
like image 39
DVG Avatar answered Sep 22 '22 19:09

DVG