这是我在stackoverflow中的第一个问题。
在我的应用程序中,我有一个实时部分,可以查看网络的运动。这是一份在线报纸,该部分显示:新文章,新评论,新投票,新辩论.....网络上发生的所有事情。
我有这个代码:
def index
@objects = Article.find(:all, :conditions => { :created_at => (Time.now-48.hours)..(Time.now), :published => true })
@objects = @objects + Debate.find(:all, :conditions => { :created_at => (Time.now-48.hours)..(Time.now), :active => true })
@objects = @objects + Event.find(:all, :conditions => { :created_at => (Time.now-48.hours)..(Time.now), :active => true })
@objects = @objects + Comment.find(:all, :conditions => { :created_at => (Time.now-48.hours)..(Time.now), :active => true })
@objects = @objects + Vote.find(:all, :conditions => { :created_at => (Time.now-48.hours)..(Time.now) })
@objects.sort! {|x,z| x.created_at <=> z.created_at}
@objects.reverse!
end
我在过去 48 小时内加载了所有内容。我一直在阅读有关在 rails 中缓存的信息,因为我认为这不是我的解决方案。
我该怎么做才能更快地加载此列表?因为现在需要 7 或 8 秒...
谢谢大家的:D
一些注意事项:
-
find(:all)
已弃用。请改用where()
。 - 而不是执行 5 个数据库调用将它们迁移到一个数据库调用中(如果需要,请为此创建 SQL 查询)。
- 确保为表中的日期列编制索引。
- 不要排序和反转排序。而是替换
y <=> x
以便它按照您需要的方式排序。
希望对您有所帮助。