× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

ActiveRecord: Use Subqueries instead of literal IN clause values

<p>I see people writing ActiveRecord queries like this:</p> <p><strong><span style="color:rgb(51, 51, 51)">matches = Match.where(start_date: '2014-02-18')</span></strong></p> <p><strong><span style="color:rgb(51, 51, 51)">Innings.where(match_id: matches.pluck(&amp;:id))</span></strong></p> <p>This generates two queries, one to fetch the list of IDs, another to get the innings details. To make it efficient, try this:</p> <p><strong><span style="color:rgb(51, 51, 51)">Innings.where(match: matches)</span></strong></p> <p><span style="color:rgb(51, 51, 51)">Rails will generate the appropriate sub queries based on the model relationship.</span></p> <p>For more details, read my <a href="http://blog.emaillenin.com/2014/12/advanced-queries-using-activerecord-in-rails.html">blog post</a>.</p>
comments powered by Disqus