sql - Rails 4 按 has_many 计数排序

标签 sql ruby-on-rails postgresql ruby-on-rails-4

在我的例子中,用户通过友谊与其他用户相关。我想按照他们拥有的 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/

相关文章:

ruby-on-rails - ruby 刚刚死于 "ActiveRecord::Base.establish_connection"

mysql : how to calculate business hrs between two timestamps and neglect weekends

sql - 使用SQL将值插入特定行

sql - U-SQL 如何为每个日期选择前 3 个异常(exception)

ruby-on-rails - 删除或更改 Trix Editor 上传图像的宽度和高度属性

postgresql - 复制架构并在同一数据库中创建具有不同名称的新架构

mysql - 我如何知道选择左连接时 'hit' 范围内的哪个值?

ruby-on-rails - 将设计与 Mongoid 集成

ruby-on-rails - 在 url_for 中使用过期时的 Amazon S3 无效日期

Mysql(和 Postgresql)在 where = 1 和 in(1) 上的性能