I have this bit of code where each project can be voted on. In my views I want to list each project by the order of votes from highest to lowest.
I found one way, but is there a better way to do this?
My way:
Controller
class Admin::ProjectsController < ApplicationController
def index
@projects = Project.all.sort_by { |project| project.votes.count }
end
end
Views
- @projects.each do |project|
%li= project.name
%li= project.teacher_firstname
%li= project.teacher_lastname
%li= project.votes.count
I was trying to do something along the lines of Project.votes.all.order(:desc)
but obviously that doesn't work, but that's what I want to try to do.
And then someone pointed me to :counter_cache but that seems a little too much just to count. No need to add a count column.
Any other suggestions?
Update Okay so two things
@jgautsch's worked, but I'm curious, it's a class method wouldn't I want to make this an instance method? Or would it not matter? Just take off self? I sometimes get confused (as much as read articles on this) of when it's appropriate for instance verses class method.
Also, I noticed that I only get projects that have been voted on. How would I continue to display them even if there are 0 votes? I even took out the
limit
and thenum
argument