15

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.

roman
  • 5,100
  • 14
  • 44
  • 77

5 Answers5

32

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
Lookchin
  • 478
  • 4
  • 7
9

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
DVG
  • 17,392
  • 7
  • 61
  • 88
1

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.

DVG
  • 17,392
  • 7
  • 61
  • 88
Bijendra
  • 9,467
  • 8
  • 39
  • 66
  • Trying 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') => #` – roman Jul 06 '12 at 09:42
  • This was an issue which has been fixed, just check this https://github.com/EppO/rolify/commit/da1ec59acda83b9114aeb410c99b1ce6e0866648 – Bijendra Jul 06 '12 at 09:53
  • Using resourcify in user model breaks succh methods as `all`, `first` etc. When i call User.all i get `NoMethodError: undefined method `find_or_create_by' for #` – roman Jul 06 '12 at 11:00
  • @innocent_rifle try to use rolify for User model and add roles using user instance. check https://github.com/EppO/rolify/issues/69 – Bijendra Jul 06 '12 at 11:54
1

If you need to use joins, try this:

User.with_role(:admin).joins(:other_table).(other_table:{some_field: true})
webaholik
  • 1,619
  • 1
  • 19
  • 30
0

if you need an aditional "where"

@courriers = User.where.not(latitude: nil, longitude:nil ).with_role :Courrier
Van Mart
  • 3,002
  • 1
  • 10
  • 5