按共同关联数排序(Rails)

背景:我有post和用户,都有很多社区。

目标:对于任何给定的用户,我想返回一组post,按照post与用户共有的社区数量排序(更多社区的post更高)

我当前的尝试(使用排序方法)有效:

Post.includes(:community_posts).where(community_posts: { community_id: current_user.community_ids }).sort{ |x,y| (y.community_ids & current_user.community_ids).length  (x.community_ids & current_user.community_ids).length } 

但有没有更好/更有效的方法来做到这一点?

我对更好/更高效的理解是你想要在数据库中执行排序,而不是Ruby。

这是一个(更简单的?)查询,只返回与用户共同的社区的post。

 current_user.posts.joins(:communities).merge(current_user.communities) 

merge过滤joins ,这是我最喜欢的新(对我) ActiveRecord技巧之一 。

好的,那么我如何应用类似的方法来按照共同的社区数量进行排序,而不仅仅是过滤? 在这里,这样做:

 current_user.posts.joins(:communities).where(communities: {id: current_user.community_ids}).select('posts.*, COUNT(distinct communities.id) AS community_count').group('posts.id').order('community_count DESC') 

joins为每个communities_posts创建单独的Post结果,然后我们使用groupCOUNT在数据库中通过用户和post之间的不同匹配社区对这些结果进行分组。

值得注意的是,由于select ,返回的每条记录看起来都像一个post,但也响应post.community_count