Find all users with specific role using rolify
10,288
Solution 1
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
Solution 2
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
Solution 3
Have you mentioned resourcify in the models in order to put roles on
class User < ActiveRecord::Base
resourcify
end
With this you can use with_role and find_roles class methods.
Comments
-
roman almost 2 years
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.
-
Bijendra almost 12 yearsAre you able to perform other operations using rolify.
-
roman almost 12 years@GhostRider Other operations such ad adding a role to a user works properly.
-
Bijendra almost 12 yearsjust check my ans below.. it should fix the issue
-
-
roman almost 12 yearsTrying to do it like this gives the following:
User Load (0.3ms) SELECT
users.* FROM
users` INNER JOIN "roles" ON "roles"."resource_type" = 'User' WHERE (roles.name = 'user' AND roles.resource_type = 'User') => #<ActiveRecord::Relation:0x36e47c4>` -
Bijendra almost 12 yearsThis was an issue which has been fixed, just check this github.com/EppO/rolify/commit/…
-
roman almost 12 yearsUsing resourcify in user model breaks succh methods as
all
,first
etc. When i call User.all i getNoMethodError: undefined method
find_or_create_by' for #<Rolify::Adapter::ResourceAdapter:0x00000005ed3870>` -
Bijendra almost 12 years@innocent_rifle try to use rolify for User model and add roles using user instance. check github.com/EppO/rolify/issues/69
-
Van Mart over 7 yearswith "where" @courriers = User.where.not(latitude: nil, longitude:nil ).with_role :Courrier