Nasty deep nested loop in Rails

Posted by CalebHC on Stack Overflow See other posts from Stack Overflow or by CalebHC
Published on 2010-04-10T04:05:41Z Indexed on 2010/04/10 4:13 UTC
Read the original article Hit count: 421

Filed under:
|
|

I have this nested loop that goes 4 levels deep to find all the image widgets and calculate their sizes. This seems really inefficient and nasty! I have thought of putting the organization_id in the widget model so I could just call something like organization.widgets.(named_scope), but I feel like that's a bad short cut. Is there a better way? Thanks

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

© Stack Overflow or respective owner

Related posts about rails

Related posts about ruby-on-rails