title: Querying average with a function of column in Rails
body: <p>I'm using Rails 4 in a web app, Postgresql database and squeel gem for queries.</p>
  
  <p>I have this function in my model statistic.rb</p>
  
  <pre><code>def properties_mean_ppm(mode, rooms, type, output_currency_id)
    sql_result = properties(mode, rooms, type).select{
      avg(price_dolar / property_area).as(prom)
    }
    avg = sql_result[0].prom
    final_avg = change_currency(avg, DOLAR_ID, output_currency_id)
    return final_avg.to_f
  end
  </code></pre>
  
  <p>price_dolar and property_area are columns in the properties table.
  It works fine in Rails console and displays the result, but when I use it on the controller it gives an error:</p>
  
  <blockquote>
    <p>ActiveModel::MissingAttributeError (missing attribute: id)</p>
  </blockquote>
  
  <p>And indicates the line</p>
  
  <pre><code>avg = sql_result.to_a[0].prom
  </code></pre>
  
  <p>I also tried using sql_result[0].prom or sql_result.take or sql_result.first, they all have the same error.
  The sql_result is this:</p>
  
  <pre><code>#&lt;ActiveRecord::Relation [#&lt;Property &gt;]&gt;
  </code></pre>
  
  <p>This is the action called in the controller</p>
  
  <pre><code>def properties_mean_ppm
    @statistic = Statistic.find(params[:id])
    mode = params[:mode] ? params[:mode] : ANY_MODE
    type = params[:type] ? params[:type] : ANY_TYPE
    one_room = @statistic.properties_mean_ppm(mode, 1, type, UF)
  end
  </code></pre>
  
  <p>I know how to get the result using only SQL without activerecord but that would be very inefficient for me because I have lots of filters called before in the properties() function</p>