作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我觉得这应该很简单,但是我的脑子短路了。如果我有一个代表当前用户的对象,并且想查询除当前用户之外的所有用户,考虑到当前用户有时可能为 nil
,我该怎么做?
这就是我现在正在做的:
def index
@users = User.all
@users.delete current_user
end
我不喜欢的是我正在对查询结果进行后处理。除了感觉有点不对之外,如果我将查询转换为使用 will_paginate
运行,我认为这不会很好地工作。关于如何通过查询执行此操作的任何建议?谢谢。
最佳答案
可以在 Rails 4 及更高版本中执行以下操作:
User.where.not(id: id)
你可以把它包装在一个很好的范围内。
scope :all_except, ->(user) { where.not(id: user) }
@users = User.all_except(current_user)
如果您愿意,也可以使用类方法:
def self.all_except(user)
where.not(id: user)
end
这两种方法都将返回一个 AR 关系对象。这意味着您可以链接方法调用:
@users = User.all_except(current_user).paginate
您可以排除任意数量的用户,因为 where()
也接受一个数组。
@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)
参见 API Docs 中的 where.not()
.
关于ruby-on-rails - rails ActiveRecord : Find All Users Except Current User,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672744/
我是一名优秀的程序员,十分优秀!