title: Rails: includes with polymorphic association
body: <p>I read this interesting article about <a href="http://robots.thoughtbot.com/using-polymorphism-to-make-a-better-activity-feed-in-rails">Using Polymorphism to Make a Better Activity Feed in Rails</a>.</p>
  
  <p>We end up with something like</p>
  
  <pre><code>class Activity &lt; ActiveRecord::Base
    belongs_to :subject, polymorphic: true
  end
  </code></pre>
  
  <p>Now, if two of those subjects are for example:</p>
  
  <pre><code>class Event &lt; ActiveRecord::Base
    has_many :guests
    after_create :create_activities
    has_one :activity, as: :subject, dependent: :destroy 
  end
  
  class Image &lt; ActiveRecord::Base
    has_many :tags
    after_create :create_activities
    has_one :activity, as: :subject, dependent: :destroy 
  end
  </code></pre>
  
  <p>With create_activities defined as</p>
  
  <pre><code>def create_activities
    Activity.create(subject: self)
  end
  </code></pre>
  
  <p>And with guests and tags defined as:</p>
  
  <pre><code>class Guest &lt; ActiveRecord::Base
    belongs_to :event
  end
  
  class Tag &lt; ActiveRecord::Base
    belongs_to :image
  end
  </code></pre>
  
  <p>If we query the last 20 activities logged, we can do:</p>
  
  <pre><code>Activity.order(created_at: :desc).limit(20)
  </code></pre>
  
  <p>We have a first N+1 query issue that we can solve with:</p>
  
  <pre><code>Activity.includes(:subject).order(created_at: :desc).limit(20)
  </code></pre>
  
  <p>But then, when we call guests or tags, we have another N+1 query problem.</p>
  
  <p><strong>What's the proper way to solve that in order to be able to use pagination ?</strong></p>