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

编程入门 行业动态 更新时间:2024-10-25 00:30:46
本文介绍了Rails ActiveRecord:查找除当前用户之外的所有用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我觉得这应该很简单,但我的大脑正在短路.如果我有一个代表当前用户的对象,并且想查询除当前用户之外的所有用户,我该怎么做,考虑到当前用户有时可以是 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 = @postmenters.all_except(@post.author)

请参阅API文档<中的where.not()/a>.

更多推荐

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

本文发布于:2023-10-24 17:21:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户   Rails   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!