title: How to sort by a calculated value in Activerecord?
body: <p>I have a rails API which returns JSON to my React front end. I'm trying to sort by a calculated value for each item in a collection. I have a <code>Space</code> model which has an <code>area</code> attribute and a <code>count</code> attribute. I'd like to sort the response by <code>total_area</code> which is just <code>area * count</code>. I'm able to do this using <code>sort_by</code> but the process is pretty slow even with less than 100 records: </p>
  
  <pre><code>@spaces = Space.all
  @spaces = @spaces.sort_by(&amp;:total_area) 
  </code></pre>
  
  <p>Where <code>total_area</code> is a <code>Space</code> class method:</p>
  
  <pre><code>def total_area
    self.area * self.count
  end
  </code></pre>
  
  <p>Is there anyway to do this within the database to get an improvement in speed? I've tried using the <code>order</code> method:</p>
  
  <pre><code>@spaces.order( "count * area" =&gt; :asc)
  </code></pre>
  
  <p>But I get the following postgres error: </p>
  
  <pre><code>PG::UndefinedColumn: ERROR:  column spaces.count * area does not exist
  </code></pre>
  
  <p>Is is possible to do this in the database? Any suggestions on how I can, or how I could do this sort more quickly would be very much appreciated. </p>