Rails ActiveRecord: Find All Users Except Current User

It is possible to do the following in Rails 4 and up:

User.where.not(id: id)

You can wrap it in a nice scope.

scope :all_except, ->(user) { where.not(id: user) }
@users = User.all_except(current_user)

Or use a class method if you prefer:

def self.all_except(user)
  where.not(id: user)
end

Both methods will return an AR relation object. This means you can chain method calls:

@users = User.all_except(current_user).paginate

You can exclude any number of users because where() also accepts an array.

@users = User.all_except([1,2,3])

For example:

@users = User.all_except(User.unverified)

And even through other associations:

class Post < ActiveRecord::Base
  has_many :comments
  has_many :commenters, -> { uniq }, through: :comments
end

@commenters = @post.commenters.all_except(@post.author)

See where.not() in the API Docs.


@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))