Reputation:
I'm trying to select some random users using the randumb
gem. My controller code looks like this:
@random_users = User.order_by_rand.limit(3).all
This search currently includes the current_user
in the random results. How can I exclude it ? i've tried insering an extra condition id: !current_user.id
, but it doesn't seem to work.
Upvotes: 0
Views: 175
Reputation: 4940
You can exclude a record from your query by using NOT SQL queries.
User.where.not(id: current_user.id).order_by_rand.limit(3)
And if this is going to be reusable, you can go ahead and create a simple scope like below:
# user.rb
# ex: User.exluding(current_user).order_by_rand....
scope :excluding, (lambda do |user|
return all unless user.present?
where.not(id: user.id)
end)
The folks at Thoughtbot also have a great article on these types of queries.
Update from your comment below:
To exclude followers:
# user.rb
# This will also exclude the user you pass in.
# so you will not need to chain the original scope `excluding`.
scope :recommended_users, (lambda do |user|
return all unless user.present?
where.not(id: user.following_ids << user.id)
end)
Upvotes: 2