在rails 2.3.8中,我正在尝试订购一个查询首先发表评论和投票最多的帖子。
我尝试将新方法添加到Post模型中:
def interestingness
self.comments_count + self.votes_count
end
post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to],
:order => :interestingness,
:limit => 10
)
但是这段代码给我一个未知的列错误。
我也试过这个
post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to],
:order => "SUM(comments_count+votes_count) DESC",
:limit => 10
)
这不会给我错误,但结果只有1行有0条评论和0票。
我做错了什么?
谢谢, 奥古斯托
答案 0 :(得分:2)
试试这个:
post_of_the_moment = find(:all, :select => '*, comments_count + votes_count AS total', :conditions => ["submitted_at BETWEEN ? and ?", from, to], :order => "total DESC", :limit => 10)
我还会看看你是否可以优化它,只用你真正需要的字段替换上面的*。还要检查你的MySQL索引是否正常,因为你想避免全表扫描等来计算总和。
答案 1 :(得分:0)
弄清楚我正在做的错误:顺序中的SUM()是对结果集进行分组。
这有效:
post_of_the_moment = find(:all, :conditions => ["submitted_at BETWEEN ? and ?", from, to],
:order => "(comments_count+votes_count) DESC",
:limit => 10
)
仍然不知道为什么我不能将我创建的有趣方法用作排序字段。