BACKGROUND: I have a set of Posts that can be voted on. I’d like to sort Posts according to their “vote score” which is determined by the following equation:
( (@post.votes.count) / ( (Time.now – @post.created_at) ** 1 ) )
I am currently defining the vote score as such:
def vote_score(x)
( (x.votes.count) / ( (Time.now - x.created_at) ** 1 ) )
end
And sorting them as such:
@posts = @posts.sort! { |a,b| vote_score((b) <=> vote_score((a) }
OBJECTIVE: This method takes a tremendous toll on my apps load times. Is there a better, more efficient way to accomplish this kind of sorting?
If you are using MySQL you can do the entire thing using a query:
Or:
Which would make your entire query:
P.S: You can then modify your Post class to use the SQL version of score if it is present. You can also make the score function cached in an instance so you don’t have to re-calculate it every time you ask for a post’s score:
P.S: The SQLLite3 equivalent is: