问题
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