Order by count of has_many :through items in Rails 3

时光怂恿深爱的人放手 提交于 2020-01-16 04:42:09

问题


If I have 3 models:

Model Section

Model User

has_many :votes

Model Vote

belongs_to :user

and inside ModelSection

has_many :users
has_many :votes, :through => :users

How to get the Sections list ordered by votes quantity using the AR associations?


回答1:


The most reasonable way to do this is to use a subquery written as raw SQL for ordering the result as follows...

Section.order(
  '(select count(1) from votes inner join users on votes.user_id=users.id where users.section_id=sections.id)'
)



回答2:


Section.joins(users: :votes).group(:id).order('COUNT(*)')


来源:https://stackoverflow.com/questions/11623226/order-by-count-of-has-many-through-items-in-rails-3

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