使用rolify查找具有特定角色的所有用户

时间:2012-07-05 17:18:40

标签: ruby-on-rails ruby permissions gem roles

使用rolify时,如何让所有用户具有特定角色?我尝试过以下但没有帮助:

User.with_role :admin

我收到以下错误:

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

无法找到任何方法。

5 个答案:

答案 0 :(得分:25)

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

User.with_role :admin

答案 1 :(得分:9)

我会问这个用户的角色

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

答案 2 :(得分:1)

您是否曾在模型中提到resourcify以便将角色置于

class User < ActiveRecord::Base
  resourcify
end

有了这个,你可以使用with_role和find_roles类方法。

答案 3 :(得分:0)

如果你需要一个aditional“where”

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

答案 4 :(得分:0)

如果您需要使用联接,请尝试以下操作:

User.with_role(:admin).joins(:other_table).(other_table:{some_field: true})