Ruby on rails 查找在Rails中没有post的用户

Ruby on rails 查找在Rails中没有post的用户,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,这是数据库关系: class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user end 但是,我想知道是否有任何方法可以通过只使用一个查询来优化它 谢谢 这将导致一个查询,该查询将获取所有尚未发布帖子的用户: User.includes(:posts).references(:posts).where('posts.id IS NUL

这是数据库关系:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end
但是,我想知道是否有任何方法可以通过只使用一个查询来优化它


谢谢

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

User.includes(:posts).references(:posts).where('posts.id IS NULL')
另一个解决方案是:

User.where('NOT EXISTS(SELECT 1 FROM posts WHERE user_id = users.id)')
由于这是一个在任何地方都要使用的相当复杂的查询,您可以将其放置在
用户
中的命名范围内:

class User < ActiveRecord::Base
  scope :without_posts, -> { where('NOT EXISTS(SELECT 1 FROM posts WHERE user_id = users.id)') }
end
我想试试这样的东西

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

返回所有拥有0篇文章的用户。

使用rails 6.1,更简单:

User.where.missing(:posts)

这似乎在Postgres中不起作用:
PG::GroupingError:ERROR:WHERE中不允许使用聚合函数
注意:第一个函数不适用于PostgreSQL(不返回任何结果),但是带有子查询的
不存在
可以很好地工作。更类似Rails的方法可能是
User.includes(:posts)。WHERE(posts:{id:nil}).references(:posts)
。这应该可以解决任何特定于数据库的问题,哈希将在数据库适配器级别处理(我相信)。
User.without_posts
User.joins(posts).where("count(posts.id) = 0")