Rails 3 - 多对多条件下模型用户和角色的数据库查询

发布于 2024-12-28 15:56:57 字数 849 浏览 5 评论 0原文

我有两个实体。用户和角色。我正在使用 Devise 和 CanCan。 他们是多对多的关系。

用户有很多角色。 角色之一是“管理员”。我使用以下方法验证我的用户是否是管理员:

if (user.role? :administrator) .... #this is already implemented and working

我必须验证系统上同一部门中不存在超过 2 个管理员。为此,我创建了一个自定义验证方法:

class User < ActiveRecord::Base
    validate :maximum_numbers_of_admins if self.role? :administrator
    belongs_to :department

    def maximum_numbers_of_admins
        #Some code here
    end

在该方法中,我应该计算具有管理员角色的用户数量(不包括我自己)。 我不知道如何设置我的 find 方法的 :conditions 来获取这个数字。

这是Role类的规范:

# == Schema Information
#
# Table name: roles
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

用户和Role之间存在多对多的关系。 (表roles_users) 有什么帮助吗?

谢谢

I have two entities. User and Role. I am using Devise and CanCan.
They are in a many to many relationship.

User has a lot of roles.
One of the roles is "Administrator". I verify if my user is an administrator using:

if (user.role? :administrator) .... #this is already implemented and working

I have to validate that never exists more than 2 administrator in the same department on the system. For that purpose I created a custom validate method:

class User < ActiveRecord::Base
    validate :maximum_numbers_of_admins if self.role? :administrator
    belongs_to :department

    def maximum_numbers_of_admins
        #Some code here
    end

In that method I should count the number of Users that have role administrator (without counting myself).
I don't know how to set the :conditions of my find method to get this number.

This is the specification of the Role class:

# == Schema Information
#
# Table name: roles
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

There is a many to many relationship between users and Roles. (Table roles_users)
Any help with that?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小帐篷 2025-01-04 15:56:57

可能是这样的:

def maximum_numbers_of_admins
    if Role.find(:conditions => ['name = ?', 'Administrator']).users.count < 2
      return true
    else
      return false
    end
end

It could be something along this lines:

def maximum_numbers_of_admins
    if Role.find(:conditions => ['name = ?', 'Administrator']).users.count < 2
      return true
    else
      return false
    end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文