按共同关联数排序(Rails)

neo*_*eon 3 sorting activerecord ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

背景:我有帖子和用户,都有很多社区.

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

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

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 }
Run Code Online (Sandbox Code Playgroud)

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

Car*_*rew 6

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

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

current_user.posts.joins(:communities).merge(current_user.communities)
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

joins每个communities_posts创建一个单独的后的结果,则我们使用groupCOUNT到基团的那些的结果,在数据库中,由用户和柱之间不同匹配的社区.

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