71

I feel this should be very simple but my brain is short-circuiting on it. If I have an object representing the current user, and want to query for all users except the current user, how can I do this, taking into account that the current user can sometimes be nil?

This is what I am doing right now:

def index
  @users = User.all
  @users.delete current_user
end

What I don't like is that I am doing post-processing on the query result. Besides feeling a little wrong, I don't think this will work nicely if I convert the query over to be run with will_paginate. Any suggestions for how to do this with a query? Thanks.

1
  • 2
    In my opinion when I query for something I should let the part of my application optimized for querying handle that: the database. So post-processing the results of a query to further filter it, to me, is putting the logic in the wrong place.
    – SingleShot
    Sep 27, 2013 at 19:47

12 Answers 12

170

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.

7
  • 1
    So does an upvote count eventually overtake an accepted answer?
    – wurde
    Sep 21, 2015 at 14:17
  • @wurde no :D - but it will be up there, so people will see what answer users get the most value from.
    – Mohamad
    Nov 13, 2015 at 15:53
  • Should place a banner on accepted answers that the community doesn't agree with. Similar to how government requires banners on cigarettes cartons.
    – wurde
    Nov 13, 2015 at 15:58
  • @wurde I think that's a great idea. Do you mind submitting it to meta, please? meta.stackoverflow.com
    – Mohamad
    Nov 13, 2015 at 17:13
  • Done. :) - On second thoughts, having read some of those comments, there are cases where the most upvoted answer is not the best in the context of the question, although it may be a better way of doing things... tough one!
    – Mohamad
    Nov 13, 2015 at 20:17
32
@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
1
  • Thanks for the named_scope suggestion. It did clean up the controller a bit and made it less ugly when "upgrading" to will_paginate. Thanks again.
    – SingleShot
    Apr 20, 2010 at 6:22
16

You can also create named_scope, e.g. in your model:

named_scope :without_user, lambda{|user| user ? {:conditions => ["id != ?", user.id]} : {} }

and in controller:

def index
  @users = User.without_user(current_user).paginate
end

This scope will return all users when called with nil and all users except given in param in other case. The advantage of this solution is that you are free to chain this call with other named scopes or will_paginate paginate method.

2
  • This is the best answer. Keep data in scopes as long as possible. Also, this is how most queries will work in Rails 3 with Arel.
    – Gdeglin
    May 20, 2010 at 22:36
  • 1
    Use class methods instead scope's lambda with params
    – Hauleth
    Jul 9, 2013 at 23:36
7

Here is a shorter version:

User.all :conditions => (current_user ? ["id != ?", current_user.id] : [])
1
  • I took the answer from user jdl, his comment about named scopes, and your refinement and am now happy. The controller is pretty clean, though the named_scoped is a bit ugly. After adding will_paginate here's my query: User.all_except(current_user).paginate(:page => params[:page])
    – SingleShot
    Apr 20, 2010 at 6:27
6

One note on GhandaL's answer - at least in Rails 3, it's worth modifying to

scope :without_user, lambda{|user| user ? {:conditions => ["users.id != ?", user.id]} : {} }

(the primary change here is from 'id != ...' to 'users.id !=...'; also scope instead of named_scope for Rails 3)

The original version works fine when simply scoping the Users table. When applying the scope to an association (e.g. team.members.without_user(current_user).... ), this change was required to clarify which table we're using for the id comparison. I saw a SQL error (using SQLite) without it.

Apologies for the separate answer...i don't yet have the reputation to comment directly on GhandaL's answer.

3

Very easy solution I used

@users = User.all.where("id != ?", current_user.id)
2

ActiveRecord::QueryMethods#excluding (Rails 7+)


Starting from Rails 7, there is a new method ActiveRecord::QueryMethods#excluding.

A quote right from the official Rails docs:

excluding(*records)

Excludes the specified record (or collection of records) from the resulting relation. For example:

Post.excluding(post)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" != 1

Post.excluding(post_one, post_two)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" NOT IN (1, 2)

This can also be called on associations. As with the above example, either a single record of collection thereof may be specified:

post = Post.find(1)
comment = Comment.find(2)
post.comments.excluding(comment)
# SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 AND "comments"."id" != 2

This is short-hand for .where.not(id: post.id) and .where.not(id: [post_one.id, post_two.id]).

An ArgumentError will be raised if either no records are specified, or if any of the records in the collection (if a collection is passed in) are not instances of the same model that the relation is scoping.

Also aliased as: without


Sources:

1

User.all.where("id NOT IN(?)", current_user.id) will through exception undefined method where for #<Array:0x0000000aef08f8>

User.where("id NOT IN (?)", current_user.id)
0

Another easy way you could do it:

@users = User.all.where("id NOT IN(?)", current_user.id)
0

an array would be more helpful

arrayID[0]=1

arrayID[1]=3

User.where.not(id: arrayID)

0

User.where(:id.ne=> current_user.id)

-5

What you are doing is deleting the current_user from the @users Array. This won't work since there isn't a delete method for arrays. What you probably want to do is this

def index
  @users = User.all
  @users - [current_user]
end

This will return a copy of the @users array, but with the current_user object removed (it it was contained in the array in the first place.

Note: This may not work if array subtraction is based on exact matches of objects and not the content. But it worked with strings when I tried it. Remember to enclose current_user in [] to force it into an Array.

3
  • Thanks for your answer. The code example I submitted does in fact work because there actually is a delete method on Array. Unfortunately your suggestion doesn't quite achieve what I am looking for. Thanks again.
    – SingleShot
    Apr 20, 2010 at 5:44
  • 3
    >> Array.new.methods.grep /delete/ => ["delete_at", "delete_if", "delete"]
    – user253455
    Apr 20, 2010 at 15:50
  • 2
    This answer is also incorrect because the index view partial uses the @users instance variable, which is unchanged by the - operation. It does not matter what the index method returns. (You needed to use the -= operator to change @users in place) Sep 25, 2012 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.