1

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?

ekad
  • 14,436
  • 26
  • 44
  • 46
Mr_Nizzle
  • 6,644
  • 12
  • 55
  • 85

2 Answers2

2

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)'
)
Steve Jorgensen
  • 11,725
  • 1
  • 33
  • 43
  • so ActiveRecord is not helping on this complex association case then? – Mr_Nizzle Jul 24 '12 at 04:33
  • 1
    Well, not for this particular sorting requirement anyway. It's presumably quite useful in regard to other ways that your application uses these models. There presumably *is* a way to implement this sorting via some byzantine combination of AR and Arel, but it's not worth the time and effort it would take to work that out -- and then it would not be especially legible or maintainable. – Steve Jorgensen Jul 24 '12 at 04:40
  • +1 Steve, very useful answer. I'm trying to do something similar but with another level of has_many through: [ http://stackoverflow.com/questions/19537378/ordering-nested-has-many-through-by-count-of-associations ]. Do you have any thoughts on how I can extend your SQL for that purpose? Thanks! – djoll Oct 23 '13 at 10:30
0
Section.joins(users: :votes).group(:id).order('COUNT(*)')