如果你正在使用MySQL,你可以使用查詢做整個事情:
SELECT posts.id,
(COUNT(votes.id)/(TIME_TO_SEC(NOW()) - TIME_TO_SEC(posts.created_at))) as score
FROM posts INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
ORDER BY score DESC
或者:
class Post
scope :with_score, select('posts.*')
.select('(COUNT(votes.id)/(TIME_TO_SEC(NOW()) - TIME_TO_SEC(posts.created_at))) as score')
.joins(:votes)
.group('posts.id')
.order('score DESC')
end
這會使你的整個查詢:
@posts = Post.with_score.all
P.S:然後,您可以修改Post類以使用分數的SQL版本(如果存在)。您也可以在實例中緩存的得分功能,這樣你就不必每次你問一個職位的得分時間重新計算的話:
class Post
def score
@score ||= self[:score] || (votes.count/(Time.now.utc - x.created_at.utc)
end
end
PS:本SQLLite3相當於是:
strftime('%s','now') - strftime('%s',posts.created_at)
有沒有理由讓你的等式提升到1的冪次?這似乎沒有必要。 – nzifnab 2011-03-13 21:49:53
你還有兩個額外的'('在你發佈的最後一個代碼中, – Dogbert 2011-03-13 21:55:36
你是對的,我一直在玩弄價值觀,在發佈權力的時候碰巧是1 - 沒有特別的理由。括號 – neon 2011-03-13 21:57:47