Rails 3.按比赛计数排序(多对多)

问题描述:

我在两个模型之间有很多联系:

I have a many to many association between two models:

class User < ActiveRecord::Base
  has_many :user_works
  has_many :works, through: :user_works
end   

class UserWork < ActiveRecord::Base
  belongs_to :user
  belongs_to :work
end    

class Work < ActiveRecord::Base
  has_many :user_works
  has_many :users, through: :user_works
end

我有一个按作品分类的过滤器,其中包含多个作品(编号).

I have a filter by works, containing several works (ids).

我的任务是按作品过滤用户并按匹配数对他们进行排序.

My task is to filter users by works and order them by count of matches.

谢谢.

我想您需要按工作分组,并按计数排序

I guess you need to group by works, and order by count

这是从较少的作品到更多的作品的排序方式:

That's how to sort from less works to more:

User.joins(:works).group("user_works.user_id").order("COUNT(*)") 

这是从更多作品到更少作品的排序方式:

That's how to sort from more works to less:

User.joins(:works).group("user_works.user_id").order("COUNT(*) DESC") 

更新. 如果您想进行一些额外的过滤,只需添加where子句

Upd. If you want to have some extra filtering just add where clause

User.joins(:works).where("user_works.work_id in #{filter_string}").group("user_works.user_id").order("COUNT(*) DESC")