在我的例子中,用户通过友谊与其他用户相关。我想按照他们拥有的 friend /友谊的数量对我的用户进行排序。
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
注意在我的例子中,我使用的是 postgres
我正在使用
a = User.all.collect {|x| [x.id, x.friends.length]};
a = a.sort {|x,y| y[-1] <=> x[-1]}
其中 x.friends
是一种通过 Friendship.where('friend_id = ? OR user_id = ?', self, self)
返回所有好友的方法。我认为这是次优的,因为它会为每个用户发出请求。
最佳答案
我不确定我的请求能否正常工作,因为我现在无法在真实数据库上进行测试。但是你应该这样做:
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)")
它只适用于 PostgreSQL 9.1 及更高版本。
关于sql - Rails 4 按 has_many 计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638415/