代码之家  ›  专栏  ›  技术社区  ›  SingleShot

Rails ActiveRecord:查找除当前用户之外的所有用户

  •  56
  • SingleShot  · 技术社区  · 16 年前

    我觉得这应该很简单,但我的大脑对它短路了。如果我有一个表示当前用户的对象,并且希望查询除当前用户以外的所有用户,那么考虑到当前用户有时可能是 nil

    这就是我现在正在做的:

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

    我不喜欢的是我正在对查询结果进行后处理。除了感觉有点不对劲之外,如果我将查询转换为使用 will_paginate

    11 回复  |  直到 16 年前
        1
  •  156
  •   Mohamad    6 年前

    在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
    

    @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)
    

    看到了吗 where.not() 在 API Docs .

        2
  •  32
  •   Hardryv    16 年前
    @users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
    
        3
  •  16
  •   Jakub Kosiński    16 年前

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

    在控制器中:

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

    当使用nil调用时,此作用域将返回所有用户,在其他情况下,将返回除param中给定的用户以外的所有用户。此解决方案的优点是,您可以自由地将此调用与其他命名作用域链接起来,也可以对paginate方法进行分页。

        4
  •  7
  •   Harish Shetty    16 年前

    User.all :conditions => (current_user ? ["id != ?", current_user.id] : [])
    
        5
  •  6
  •   Steve Bourne    15 年前

    关于GhandaL的答案,至少在Rails3中,值得修改一下

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

    (此处的主要更改来自'id!=…'到'users.id!=…';也是作用域而不是命名的\u作用域(适用于Rails 3)

    为单独的回答道歉…我还没有声誉直接评论甘达尔的回答。

        6
  •  3
  •   Phil Duffney    10 年前

    我用的很简单的方法

    @users = User.all.where("id != ?", current_user.id)
    
        7
  •  1
  •   user3202320    10 年前

    User.all.where(“id NOT IN(?),current\u User.id)将通过异常 未定义的方法,其中 #<Array:0x0000000aef08f8>

    User.where("id NOT IN (?)", current_user.id)
    
        8
  •  0
  •   Vasfed SAJITHA MARIYAM    10 年前

    另一种简单的方法:

    @users = User.all.where("id NOT IN(?)", current_user.id)
    
        9
  •  0
  •   Asif Alam    9 年前

    数组会更有帮助

    数组ID[1]=3

        10
  •  0
  •   Lana Kushnir    8 年前

    User.where(:id.ne=>当前用户id)

        11
  •  -5
  •   Fotios    16 年前

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

    这将返回@users数组的一个副本,但是删除了当前的\u user对象(它首先包含在数组中)。

    注意:如果数组减法是基于对象的精确匹配,而不是基于内容,则这可能不起作用。但我试的时候,它是用弦做的。请记住将当前用户括在[]中,以将其强制放入数组中。

    推荐文章