查找在Rails中没有帖子的用户 [英] Find user who has no post in Rails

查看:51
本文介绍了查找在Rails中没有帖子的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与数据库的关系:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

我遇到了一个功能,我想查询所有还没有任何帖子的用户.我知道我们可以用以下方法做到这一点:

I come across a functionality where I want to query all the users who don't have any posts yet. I know that we can do this with something like this:

users = User.all
users.each do |user|
  unless user.posts.any?
    # do something when user don't have any post.
  end
end

但是,我想知道是否有任何方法可以仅通过使用一个查询来对此进行优化.

However, I wonder if there is any way to optimize this by using one query only.

谢谢!

推荐答案

这将导致一个查询,该查询将获取尚无帖子的所有用户:

This results in a single query which fetches all users who don't have posts yet:

User.includes(:posts).references(:posts).where('posts.id IS NULL')

另一个解决方法是:

User.where('NOT EXISTS(SELECT 1 FROM posts WHERE user_id = users.id)')

由于这是一个在任何地方都使用的相当复杂的查询,因此可以将其放在 User 中的命名范围内:

Since this is a rather complex query to use everywhere, you can place this inside a named scope in User:

class User < ActiveRecord::Base
  scope :without_posts, -> { where('NOT EXISTS(SELECT 1 FROM posts WHERE user_id = users.id)') }
end

现在您可以在应用程序的其他地方使用此范围:

Now you can use this scope elsewhere in your application:

User.without_posts

这篇关于查找在Rails中没有帖子的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆