问题描述
我觉得这应该很简单,但我的大脑正在短路.如果我有一个代表当前用户的对象,并且想查询除当前用户之外的所有用户,我该怎么做,考虑到当前用户有时可能是nil
?
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
我不喜欢的是我正在对查询结果进行后处理.除了感觉有点不对劲,如果我将查询转换为使用 will_paginate
运行,我认为这不会很好地工作.有关如何通过查询执行此操作的任何建议?谢谢.
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.
推荐答案
在 Rails 4 及更高版本中可以执行以下操作:
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
这两种方法都将返回一个 AR 关系对象.这意味着您可以链接方法调用:
Both methods will return an AR relation object. This means you can chain method calls:
@users = User.all_except(current_user).paginate
您可以排除任意数量的用户,因为 where()
也接受一个数组.
You can exclude any number of users because where()
also accepts an array.
@users = User.all_except([1,2,3])
例如:
@users = User.all_except(User.unverified)
甚至通过其他关联:
class Post < ActiveRecord::Base
has_many :comments
has_many :commenters, -> { uniq }, through: :comments
end
@commenters = @post.commenters.all_except(@post.author)
这篇关于Rails ActiveRecord:查找除当前用户以外的所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!