【问题标题】:Find all users with specific role using rolify使用 rolify 查找具有特定角色的所有用户
【发布时间】:2012-07-06 03:38:14
【问题描述】:

使用 rolify 时如何获取具有特定角色的所有用户?我尝试了以下方法,但没有帮助:

User.with_role :admin

我收到以下错误:

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

找不到任何方法。

【问题讨论】:

  • 你是否可以使用 rolify 执行其他操作。
  • @GhostRider 向用户添加角色等其他操作正常工作。
  • 看看我下面的答案..它应该可以解决问题

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


【解决方案1】:

您可以使用带有 User 类的 with_role 方法来查找在 3.1.0 版本中具有角色的所有用户。

User.with_role :admin

【讨论】:

  • with "where" @courriers = User.where.not(latitude: nil, longitude:nil ).with_role :Courrier
【解决方案2】:

我会为它的用户询问角色

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

【讨论】:

    【解决方案3】:

    您是否在模型中提到了资源化以赋予角色

    class User < ActiveRecord::Base
      resourcify
    end
    

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

    【讨论】:

    • 尝试这样做会得到以下结果: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') => #<:relation:0x36e47c4>`
    • 这是一个已修复的问题,请查看github.com/EppO/rolify/commit/…
    • 在用户模型中使用 resourcecify 会破坏 allfirst 等成功方法。当我调用 User.all 时,我会为 #<:adapter::resourceadapter>NoMethodError: undefined method find_or_create_by': 0x00000005ed3870>`
    • @innocent_rifle 尝试将 rolify 用于用户模型并使用用户实例添加角色。检查github.com/EppO/rolify/issues/69
    【解决方案4】:

    如果您需要额外的“位置”

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

    【讨论】:

      【解决方案5】:

      如果你需要使用连接,试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 2012-10-26
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多