Mr_Nizzle
Mr_Nizzle

Reputation: 6714

Order by count of has_many :through items in Rails 3

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?

Upvotes: 1

Views: 531

Answers (2)

Ruslan Khamidullin
Ruslan Khamidullin

Reputation: 1

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

Upvotes: 0

Steve Jorgensen
Steve Jorgensen

Reputation: 12361

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

Upvotes: 2

Related Questions