获取没有帖子或没有活动帖子的用户

Get users with no postings or no active postings

我有一个 rails 架构,我有用户 table 和帖子 table。我试图让所有没有帖子或没有活动帖子的用户。 Active 是帖子上的一列,可以是真也可以是假。以下是正确的吗?

User.joins('LEFT JOIN postings on users WHERE postings.user_id = users.id').where('postings.id = NULL').or(where('postings.active = false')).

问题是,如果用户有任何活跃的帖子:是的,我不想要它们,因为他们至少有一个活跃的帖子。我目前正在找回拥有 active: false posts 和 active:true posts.

的用户

我认为您无需过滤 left_join,这样我们就可以按用户分组并对所有帖子状态求和,如果总和为零,则表示该用户不包含任何活动帖子。

User.left_joins(:postings)
.group("users.id")
.having("postings.active IS NULL OR SUM(CAST(postings.active AS TINYINT)) = 0")

# having("SUM(case when postings.active IS NULL OR postings.active = false then 0 else 1 end) = 0")