0

我基本上有一个 Document 模型,它有_many Pages,我有一个视图,我需要枚举一堆文档(例如 300)并为每个页面制作一个按钮。(我想使用 DataTables jQuery 插件进行分页客户端,以便表格可以排序和搜索)。问题是,如果我尝试枚举每个文档中每个页面的所有按钮,则渲染时间超过 10 秒,这只是没有用。

快速进行这种嵌套集合渲染有什么“技巧”吗?我是否应该只缓存每个文档的片段(一旦创建它们就不会发生太大变化)?或者这对于 Rails 部分来说只是一个糟糕的情况,我最好的选择是在 DataTables 中进行一些客户端渲染作为分页的一部分?

编辑:我已经包含了关联,所以我没有 N+1 查询问题,这不是问题。我尝试了缓存,现在看来这可能是我的解决方案,因为这个索引页面经常在每添加几个文档之间重新加载,所以它永远不必重建所有部分的完整缓存。

4

1 回答 1

0

对缓存的迫切需求似乎是一种代码味道。代替猜测,您是否尝试过分析?(例如http://hiltmon.com/blog/2012/02/27/quick-and-dirty-rails-performance-profiling/

gem 'ruby-prof'

定义分析器:

# /lib/development_profiler.rb

class DevelopmentProfiler
  def self.prof(file_name)

    RubyProf.start
    yield
    results = RubyProf.stop

    # Print a flat profile to text
    File.open "#{Rails.root}/tmp/performance/#{file_name}-graph.html", 'w' do |file|
      RubyProf::GraphHtmlPrinter.new(results).print(file)
    end

    File.open "#{Rails.root}/tmp/performance/#{file_name}-flat.txt", 'w' do |file|
      # RubyProf::FlatPrinter.new(results).print(file)
      RubyProf::FlatPrinterWithLineNumbers.new(results).print(file)
    end

    File.open "#{Rails.root}/tmp/performance/#{file_name}-stack.html", 'w' do |file|
      RubyProf::CallStackPrinter.new(results).print(file)
    end
  end
end

用...包装您的视图逻辑

DevelopmentProfiler::prof("render-profiling") do
  # Your slow code here
end

编辑 - 一个额外的想法:因为你的模型数据不太可能改变,一次吃渲染成本可能会更好。您可以在 after_save 回调中静态生成整个呈现的页面。然后只需为后续请求提供该单个文件。

虽然如果向更传统的缓存收费不是很大的不便,但这可能比它的价值更麻烦。

于 2013-04-24T15:27:36.617 回答