title: rails 4 eager loading heavy association
body: <p>I have an association between rails models.</p>
  
  <p>There are three models which describe <code>product</code> properties:</p>
  
  <p><code>Property</code> is associating the models, each property has a name and value.</p>
  
  <pre><code>class Property &lt; AR::Base
    belongs_to :product
    belongs_to :property_name
    belongs_to :property_value
  
  class PropertyName &lt; AR::Base
    has_many :properties
    validates :name, presence: true, uniqueness: true
  
  class PropertyValue &lt; AR::Base
    has_many :properties
    validates :value, presence: true, uniqueness: true
  </code></pre>
  
  <p>After searching via <a href="http://pat.github.io/thinking-sphinx/" rel="nofollow">thinking-sphinx</a> I get facets - property_values id &amp; property_names id collections.</p>
  
  <p>Using that result, I then try to find all properties for current list of <code>products</code> (to continue to filter those search results).</p>
  
  <p>In the controller I use:</p>
  
  <pre><code>@property_names = PropertyName
    .where(id: property_name_ids)
    .includes(:property_values).where('property_values.id IN (?)', property_value_ids)
  </code></pre>
  
  <p>My view:</p>
  
  <pre><code>- @property_names.each do |property_name|
    h4 = property_name.name
    - property_name.property_values.pluck(:value).uniq.each do |property_value|
      = check_box_tag ...
      = label_tag ...
  </code></pre>
  
  <p>So, eager load does not work. Rails generate a lot of (n+1) queries for the database. What's going wrong? Why includes don't work?</p>