I am building an app that allows users to post. Those posts can be upvoted and downvoted. Each post record keeps track of upvotes:integer and downvotes:integer. I want to be able to order the records by which has the most upvotes total (in other words: upvotes-downvotes). I have absolutely no idea how to do this because I do not quite understand how Class methods interact with the object they are called on. This is my attempt:
My controller:
def index
@posts = Post.find(:all).most_votes.order(vote_difference)
end
My Post.rb Model:
def self.most_votes
vote_difference = (upvotes-downvotes)
end
Any ideas on how to do this?
Turns out you can actually insert the calculation right into the .order() value: