Rails Active Record to make arithmetic calculation over a select statement
<p>I am trying to calculate values from existing table column and use it on an external variable.</p>

<p>Let my table columns be as : <code>["id","unit_price","quantity","extras_1","extras_2"]</code>
I am presenting what i want to do in rails using sql command as reference.</p>

<p>SQL Command:</p>

<pre><code>SELECT unit_price*quantity AS "regular_price", 
       unit_price*quantity-unit_price*quantity*discount AS "price_after_discount"
FROM order_details;
</code></pre>

<p>In Rails Active Record Query i tried same as:</p>

<pre><code>OrderDetail.select('unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount')
</code></pre>

<p>From the above query.i tried sorting based on derived attributes.it worked perfectly.But i cannot see the derived attribute values by querying.</p>

<p>The output i got is without the derived attributes as:</p>

<pre><code>[#&lt;OrderDetail &gt;,#&lt;OrderDetail &gt;]
</code></pre>

<p>But i need output as:</p>

<pre><code>[#&lt;OrderDetail regular_price: 43, price_after_discount: 54&gt;,#&lt;OrderDetail regular_price: 54, price_after_discount: 76&gt;]
</code></pre>

<p>I tried below query to sort the data.It sorted the data perfectly:</p>

<pre><code>OrderDetail.select('unit_price,quantity,unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount').order('regular_price desc')
</code></pre>

<p>I can access the values using below command:</p>

<pre><code>OrderDetail.select('unit_price,quantity,unit_price*quantity AS extras_1,unit_price*quantity-unit_price*quantity*discount AS extras_2')
</code></pre>

<p>above commmand worked because <code>extras_1</code> and <code>extras_2</code> are table columns.</p>

<p>But it is working when assigned to existing table column.I need derived attribute to be non-existing table column name.</p>

<p>How can i access a derived attributes values from a record.I can access them by assigning them to an existing table column.But i want the attributes name given how i want irrespective of table columns.</p>