eager loading in recursive partial ( Ruby on Rails)
<p>I have a model with a self-join: </p>

<pre><code>  class Audience &lt; ActiveRecord::Base
   has_many :children, class_name: "Audience", foreign_key: "parent_id"
   belongs_to :parent, class_name: "Audience"
  end 
</code></pre>

<p>It is a simple tree structure that is arbitrary levels deep.</p>

<p>I have been recursively printing out a form using a  partial (_checkbox_for_children.html.erb) like so: </p>

<p>Starting with ( with the knowledge of root audience): </p>

<pre><code>&lt;%= render 'checkbox_for_children', :audience =&gt; root_audience %&gt;
</code></pre>

<p>And the Partial itself(checkbox_for_children) looks like follows: </p>

<pre><code>&lt;% children = audience.children %&gt;

&lt;ul class="list-unstyled"&gt;
  &lt;% children.each do |child| %&gt;
    &lt;li&gt;
      &lt;% if child.targetable.present? %&gt;
        &lt;%= check_box_tag("demographic_data[#{child.name}]", child.demographic_id) %&gt;
        &lt;%= child.name %&gt;
        &lt;% if child.children.present? %&gt;
           &lt;%= render 'checkbox_for_children', :audience =&gt; child %&gt;
        &lt;% end %&gt;
      &lt;% else %&gt;
        &lt;%= child.name %&gt;
        &lt;% if child.children.present? %&gt;
           &lt;%= render 'checkbox_for_children', :audience =&gt; child %&gt;
        &lt;% end %&gt;
      &lt;% end %&gt;
    &lt;/li&gt;
  &lt;% end %&gt;
&lt;/ul&gt;  
</code></pre>

<p>The problem with this approach is that way too many queries are being run to render a view. I need to eagerload children somehow to manage the number of queries. Any ideas? </p>

<p>I don't think I can just pass in includes(:children) via the local variable of the partial ( I tried, it throws an error).</p>

<p>The controller is quite simple and just looks like this: </p>

<pre><code>  def add_demographic
    @relevant_providers = Provider.have_audience
    render "add_demographic"
  end
</code></pre>

<p>provider has_many audiences which has many children ( in the audience table itself)</p>