Rails中令人讨厌的深嵌套循环

Cal*_*bHC 1 ruby-on-rails nested-loops

我有这个嵌套的循环,深入4级,找到所有图像小部件并计算它们的大小.这看起来真的很低效和讨厌!我曾想过将organization_id放在widget模型中,所以我可以调用像organization.widgets这样的东西.(named_scope),但我觉得这是一个糟糕的捷径.有没有更好的办法?谢谢

class Organization < ActiveRecord::Base
...
  def get_image_widget_total
    total_size = 0
    self.trips.each do |t|
      t.phases.each do |phase|
        phase.pages.each do |page|
          page.widgets.each do |widget|
            if widget.widget_type == Widget::IMAGE
             total_size += widget.image_file_size
            end
         end
       end
     end
    end
    return total_size
  end
...
end
Run Code Online (Sandbox Code Playgroud)

vla*_*adr 6

出于性能和内存考虑,您应该考虑发布一个SELECT SUM(total_size)语句,例如

Widget.sum(
  :total_size,
  :conditions => [ 'widget_type = ? AND organization_id = ?',
    Widget::IMAGE', self.id ],
  :joins => [ :pages, :phases, :trips ]
)
Run Code Online (Sandbox Code Playgroud)