Ask A Question

Notifications

You’re not receiving notifications from this thread.

Improve multilayer nested loops

RJ McCollam asked in Databases

I have built a drilldown type screen in an application I am working on and the way I set it up initially is super inefficient and causes really slow load times. The over all concept is we are displaying a break down of 4 different models that are nested underneath each other so a user can "drilldown" into what they want to see in a nice hierarchy layout.

Here is a screenshot of how it plays out.
Image of drilldown

Currently I am making this call in my controller:

@initiatives = @company.initiatives.where("start_year <= ? AND end_year >= ?", @year, @year).order(weight: :desc)

This gives me all of my model 1's in the screenshot. I then loop through those and call model 2 for each instance of model 1. And the same thing for model 2, where I loop through all of those and find each instance of model 3.

It looks like this in the view:

<% @initiatives.each do |initiative| %>

    <% initiative.annual_priorities.order(weight: :desc).each do |annual_priority| %>

        <% annual_priority.quarterly_priorities.order(quarter: :asc).each do |quarterly_priority| %>

            <% quarterly_priority.smarts.order(due_date: :asc, weight: :desc).each do |smart| %>



            <% end %>

        <% end %>

    <% end %>

<% end %>

A super expensive way to get all this information for sure, but I am not sure what other sort of structure I could use to give me the grouping that I need this data in. How might I structure this query in my controller to be more efficient?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.