Find user who has no post in Rails

匆匆过客 提交于 2021-01-23 08:37:41

问题


This the the database relation:

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.

Thanks!


回答1:


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

Another solution is this:

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

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



回答2:


I'd try something like

User.joins(posts).where("count(posts.id) = 0")

Which returns all users that have 0 posts.



来源:https://stackoverflow.com/questions/25813171/find-user-who-has-no-post-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!