title: Is there a clean way to use ORDER BY inside an Arel NamedFunction Node?
body: <p>I'm using ActiveRecord 4.2 / Arel 6.0 / Postgres and have the following inputs:</p>
  
  <ul>
  <li>An <code>Arel::Attributes::Attribute</code> from an <code>Arel::Table</code> (<code>column</code>)</li>
  <li>Several <code>Arel::Nodes::Ordering</code> nodes (<code>orders</code>)</li>
  </ul>
  
  <p>I want to build an <code>Arel::Nodes::NamedFunction</code> with an aggregate function that includes the column specified by the <code>Attribute</code> and is ordered by the <code>Ordering</code> nodes.</p>
  
  <p>The resulting SQL could look something like:</p>
  
  <pre><code>array_agg("posts"."id" ORDER BY "posts"."published_at" DESC)
  </code></pre>
  
  <p>My current solution is to first build an <code>Arel::Nodes::SelectStatement</code>, add the column and orders to it, convert it to SQL, strip the leading <code>SELECT</code> keyword, wrap it in an <code>Arel::Nodes::SqlLiteral</code> and pass that to the <code>NamedFunction</code> node:</p>
  
  <pre><code>select = Arel::Nodes::SelectStatement.new
  select.cores.last.projections &lt;&lt; column
  select.orders = orders
  
  sql = select.to_sql.sub(/^SELECT /, '')
  literal = Arel::Nodes::SqlLiteral.new(sql)
  
  array_agg = Arel::Nodes::NamedFunction.new('array_agg', [literal])
  </code></pre>
  
  <p>Obviously, this is a huge hack.</p>
  
  <p>Keeping the <code>ORDER BY</code> outside the aggregate function is not an option, because it would conflict with the <code>GROUP BY</code> used to aggregate.</p>
  
  <p>So is there a cleaner way to achieve this without abusing <code>SelectStatement</code> / <code>SelectManager</code>?</p>