gpt4 book ai didi

ruby-on-rails - 查找在 Rails 中没有帖子的用户

转载 作者:行者123 更新时间:2023-12-01 09:56:27 25 4
gpt4 key购买 nike

这是数据库关系:

class User < ActiveRecord::Base
has_many :posts
end

class Post < ActiveRecord::Base
belongs_to :user
end

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

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

但是,我想知道是否有任何方法可以通过仅使用一个查询来优化这一点。

谢谢!

最佳答案

这会产生一个查询,该查询会获取所有还没有帖子的用户:

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

另一个解决方案是这样的:

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

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

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

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

User.without_posts

关于ruby-on-rails - 查找在 Rails 中没有帖子的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25813171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com