即使 none (rails) 按共同关联数排序

Ordering by number of associations in common even if none (rails)

我正在做一个与这个问题非常相似的难题的项目: Ordering by number of associations in common (Rails)

said ask (Neon) 的提问者写道,

BACKGROUND: I have Posts and Users, and both have many Communities.

OBJECTIVE: For any given User I'd like to return a collection of Posts, ordered by how many communities the post has in common with the user (posts with more communities in-common being higher up)

遗憾的是,该解决方案仅包含至少具有一个共同社区的帖子。我的问题需要包括按公共社区数量排序的所有帖子。

EXTENDED OBJECTIVE: 结果必须是一个 AREL 对象,其中 all 个帖子按公共社区的数量排序,包括与用户有零个共同社区的帖子(有更多共同社区的帖子在更高层)。

如果您需要包含与用户共有的社区为零的帖子,您可以使用 LEFT JOIN。要清理在 join 条件下发送的参数,我们可以在 class 方法中定义它,以便 sanitize_sql_array 方法可用:

# Post class
def self.community_counts(current_user)
  current_user.posts.joins(sanitize_sql_array(["LEFT JOIN community_posts ON community_posts.post_id = posts.id AND community_posts.community_id IN (?)", current_user.community_ids])).select("posts.*, COUNT(DISTINCT community_posts.community_id) AS community_count").group("posts.id").order("community_count DESC")
end

附加信息

一个INNER JOIN returns两个table的交集。 A LEFT JOIN returns 左侧的所有行 table(在本例中为 posts)和 returns 右侧的匹配行 table(community_posts) 但当没有匹配时它也在右侧显示 returns NULL(没有与用户社区匹配的社区的帖子)。有关插图,请参阅 this answer

据我所知,Rails 没有提供任何辅助方法来生成 LEFT JOIN。我们必须为这些写出SQL。

LEFT JOIN 等同于 LEFT OUTER JOIN (more info).