Search code examples
ruby-on-rails-3activerecordscopenamed-scope

Rails ActiveRecord Scope that is the "opposite" of another scope, or is users that "lack" a property


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?


Solution

  • 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) }