title: Flattening an array of ActiveRecord::Relation instances
body: <p>I wanted to convert a nested array of <code>ActiveRecord::Relation</code> objects, like this:</p>
  
  <pre><code># Event is a ActiveRecord::Base derived class
  r1 = [ [ Event.where(id: 1) ], Event.where(id: 1)]
  # =&gt; [ [ #&lt;ActiveRecord::Relation []&gt; ], #&lt;ActiveRecord::Relation[]&gt; ]
  </code></pre>
  
  <p>into:</p>
  
  <pre><code>[#&lt;ActiveRecord::Relation []&gt;, #&lt;ActiveRecord::Relation []&gt; ]
  </code></pre>
  
  <p><code>Array#flatten</code> is designed to do this perfectly. Unfortunately, it does not return the expected result:</p>
  
  <pre><code>r1.flatten # =&gt; []
  </code></pre>
  
  <p><code>Enumrable#map</code> does not work either:</p>
  
  <pre><code>r1.map{|m| m.limit(10) } # =&gt; []
  </code></pre>
  
  <p><code>Enumerable#flat_map</code> returns a little different result:</p>
  
  <pre><code>r1.flat_map{|m| m.limit(10) } # =&gt; [ #&lt;ActiveRecord::Relation []&gt; ]
  </code></pre>
  
  <p>Finally, looping over the array and pushing into another empty array returns the expected result:</p>
  
  <pre><code>z = []
  r1.each {|e| if e.is_a?(Array) then e.each{|x| z &lt;&lt; x} else z &lt;&lt; e end}
  # =&gt; [#&lt;ActiveRecord::Relation []&gt;, #&lt;ActiveRecord::Relation []&gt; ]
  </code></pre>
  
  <p>What causes these differences?</p>
  
  <p>I'm using</p>
  
  <ul>
  <li>ruby 2.0.0p353 (2013-11-22 revision 43784) [x86_64-darwin13.0.0]</li>
  <li>(built with gcc via RVM + Homebrew)</li>
  <li>Rails 4.0.2</li>
  <li>MacOS X Mavericks</li>
  </ul>