简体   繁体   English

Rails 4通过has_many的计数顺序

[英]Rails 4 order by count of has_many through

In my case, users are related to other users through friendships. 就我而言,用户通过友谊与其他用户相关。 I want to order my users by the number of friends/friendships they have. 我想按他们拥有的朋友/友谊的数量来排序我的用户。

class User < ActiveRecord::Base
    has_many :friendships
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
end


class Friendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, :class_name => "User"
end

NB In my case I am using postgres 注意:我使用的是postgres

I am currently using 我目前正在使用

a = User.all.collect {|x| [x.id, x.friends.length]}; 
a = a.sort {|x,y| y[-1] <=> x[-1]}

Where x.friends is a method which returns all friends via Friendship.where('friend_id = ? OR user_id = ?', self, self) . 其中x.friends是一种通过Friendship.where('friend_id = ? OR user_id = ?', self, self)返回所有朋友的方法。 I believe this is suboptimal as it makes a request per user. 我认为这不是最佳选择,因为它会向每个用户发出请求。

I am not sure that my request will work properly, because I can't test on on a real DB now. 我不确定我的请求是否会正常运行,因为我现在无法在真实的数据库上进行测试。 But you should do it like this: 但是您应该这样做:

User.select(users.*, SUM(friendships.id)).joins("INNER JOIN users as friendships ON users.id = friendships.friend_id").group(users.id).order("SUM(friendships.id)")

User.select(users.*, SUM(inverse_friendships.id)).joins("INNER JOIN users as inverse_friendships ON users.friend_id = inverse_friendships.id").group(users.id).order("SUM(inverse_friendships.id)")

It will work only with PostgreSQL 9.1 and higher. 它仅适用于PostgreSQL 9.1及更高版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM