[英]Rails 4 order by count of has_many through
就我而言,用户通过友谊与其他用户相关。 我想按他们拥有的朋友/友谊的数量来排序我的用户。
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及更高版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.