Rails的ActiveRecord的范围,它是"相反"另一范围,或者是用户的"缺少"一个属性 [英] Rails ActiveRecord Scope that is the "opposite" of another scope, or is users that "lack" a property

查看:221
本文介绍了Rails的ActiveRecord的范围,它是"相反"另一范围,或者是用户的"缺少"一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,user.rb,我在其中定义管理​​员,这是一个有管理的通过权限表中角色的用户的作用域。

I have a model for user.rb, in which I define a scope for admins, which is users that have the role of admin through a permissions table.

has_many :permissions
has_many :roles, :through => :permissions

的范围是这样的:

The scope works like this:

scope :admins, joins(:permissions).merge(Permission.admin_permissions)

我也想创建一个名为范围非管理员之类的东西,这是不具有管理员角色的所有用户。

I'd also like to make a scope called non-admins or something like that, which is all users that do NOT have the admin role.

什么是做到这一点的最简单的方法是什么?

What's the easiest way to do this?

推荐答案

一个简单的方法,它的不会高性能对于很多用户的:

An easy way, which would not be performant for a lot of users:

admin_user_ids  = User.admins.map(&:id)
non_admin_users = User.all.reject { |u| admin_user_ids.include?(u.id) }

这篇关于Rails的ActiveRecord的范围,它是"相反"另一范围,或者是用户的"缺少"一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆