2012-07-05 89 views
12

使用rolify时,如何获取具有特定角色的所有用户?我试过以下,但它并没有帮助:使用rolify查找具有特定角色的所有用户

User.with_role :admin 

我得到以下错误:

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

找不到任何方式做到这一点。

+0

您是否可以用其他rolify操作执行。 – Bijendra 2012-07-05 17:30:35

+0

@GhostRider 其他操作,例如向用户添加角色的广告可正常工作。 – RomanKapitonov 2012-07-05 17:35:44

+0

只是检查我的答案如下..它应该解决问题 – Bijendra 2012-07-05 17:53:49

回答

23

您可以将with_role方法与User类一起使用,以查找在版本3.1.0中具有角色的所有用户。

User.with_role :admin 
+0

与“where” @courriers = User.where.not(纬度:零,经度:零).with_role:Courrier – 2017-02-09 23:00:00

8

我问这个角色为它的用户

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

的with_role方法是为特定的用户实例,而不是在类级别的所有用户。如果你想实现你不得不做这样的事情:

#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 
1

有你的模型为了把角色上

class User < ActiveRecord::Base 
    resourcify 
end 

有了这个,你可以使用with_role并提到resourcify find_roles类的方法。

+0

试图这样做,这样做给出了以下内容: '用户负载(0.3ms)选择'用户'。*从'用户'INNER JOIN“角色”ON“角色“。”。“resource_type”='User'WHERE(roles.name ='user'AND roles.resource_type ='User') =>#' – RomanKapitonov 2012-07-06 09:42:03

+0

这是一个已经修复的问题,只是检查这个https://github.com/EppO/rolify/commit/da1ec59acda83b9114aeb410c99b1ce6e0866648 – Bijendra 2012-07-06 09:53:52

+0

@innocent_rifle还要检查这个https://github.com/EppO/rolify/issues/65 – Bijendra 2012-07-06 09:55:12

0

,如果你需要一个aditional的 “其中”

@courriers = User.where.not(latitude: nil, longitude:nil).with_role :Courrier 
相关问题