在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()
也接受一个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)
见API Docs页中的where.not()
页.