问题
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