开发者

Rails 3: Ordering by grouping in associated model

开发者 https://www.devze.com 2023-02-23 14:09 出处:网络
My question is similar to this but that one didn\'t get a proper answer so I\'d like to ask for myself...

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

  1. Add votes_count column to submissions migration(t.integer :votes_count, :default => 0)
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消