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