Rails 3.按比赛计数排序(多对多) [英] Rails 3. Order by count of matches (many to many)

查看:66
本文介绍了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")

这篇关于Rails 3.按比赛计数排序(多对多)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆