My question is similar to this but that one didn't get a proper answer so I'd like to ask for myself...
I have submissions and votes. Each submissio开发者_如何学运维n has many votes via the usual has_many
and belongs_to
association.
I need to sort the submissions by the number of votes they have. The votes table has an individual entry for each vote, with a submission_id
associated with each record, so I can't just sort by a single column in the associated model, and that's where I'd like your help.
Vote.all.group_by {|v| v.submission_id}.sort_by {|v| v[1].size}
Again, quick and dirty:
Vote.all.group_by {|v| v.submission_id}.sort_by {|v| v[1].size}.reverse
This is probably not the way you want to do it in production though. You might set up a counter cache in the submissions table(assuming 1 vote per record in the votes table):
- Add votes_count column to submissions migration(t.integer :votes_count, :default => 0)
- In the model(vote.rb) belongs_to :submission, :counter_cache => true
Now you can sort by votes_count in the submissions table:
Submission.order('votes_count DESC')
Use the Rails counter_cache
feature. See more here.
精彩评论