Rails 3. Order by count of matches (many to many)

守給你的承諾、 提交于 2019-12-12 19:53:04

问题


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.

Thanks in advance.


回答1:


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") 

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")


来源:https://stackoverflow.com/questions/16834399/rails-3-order-by-count-of-matches-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!