Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I believe you will need at least two AR query invocations (as you currently have) because of the <code>limit(20)</code> clause. Your queries currently gives you up to 20 Posts, AND up to 20 Projects, so doing an aggregate limit on both activity types in a single query would not give the intended result.</p> <p>I think all you need to do is use <code>eager_load</code> in the query instead of <code>includes</code> to force a single query. The differences between <code>joins</code>, <code>includes</code>, <code>preload</code>, <code>eager_load</code> and <code>references</code> methods are nicely covered <a href="http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html" rel="nofollow">here</a></p> <p>So, with AR and squeel:</p> <pre><code>def index @activities = Activity.limit(20).order { created_at.desc } @one = @activities.where{trackable_type == 'Post'}.eager_loads(trackable: [:author, :project]) @two = @activities.where{trackable_type == 'Project'}.eager_loads trackable: [:owner] @activities = @one + @two end </code></pre> <p>And without the squeel, using just regular ActiveRecord 4:</p> <pre><code>def index @activities = Activity.limit(20).order(created_at: :desc) @one = @activities.where(trackable_type: 'Post').eager_loads(trackable: [:author, :project]) @two = @activities.where(trackable_type: 'Project').eager_loads(trackable: :owner) @activities = @one + @two end </code></pre> <p>You don't need squeel, I recently ripped it out of my project because it doesn't work properly for a number of complex queries in my experience, where AR 4 and Arel were ok.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload