背景:我有帖子和用户,并且都有很多社区。p>
目标:对于任何给定的用户,我想返回一个帖子集合,按照帖子与用户共有的社区数量排序(共同社区越多的帖子越高上)
我目前的尝试(使用排序方法)有效:
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 中执行排序。
这是一个(更简单?)查询,仅返回与用户有共同社区的帖子。
current_user.posts.joins(:communities).merge(current_user.communities)
merge
过滤joins
,这是我最喜欢的新功能之一(对我而言)ActiveRecord tricks .
好的,那么我如何应用类似的方法来按共同社区的数量进行排序,而不仅仅是过滤? 这里,这样做:
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
为每个 community_posts 创建一个单独的 Post 结果,然后我们使用 group
和 COUNT
将这些结果分组,在数据库中,通过用户和帖子之间不同的匹配社区。
值得注意的是,由于 select
,返回的每条记录看起来都像一个帖子,但也会响应 post.community_count
。
关于ruby-on-rails - 按公共(public)关联数排序(Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199596/