Rails 3 - 多对多条件下模型用户和角色的数据库查询
我有两个实体。用户和角色。我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能是这样的:
It could be something along this lines: