jeudi 20 octobre 2016

Rails Active Record to make arithmetic calculation over a select statement

I am trying to calculate values from existing table column and use it on an external variable.

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

SQL Command:

SELECT unit_price*quantity AS "regular_price", 
       unit_price*quantity-unit_price*quantity*discount AS "price_after_discount"
FROM order_details;

In Rails Active Record Query i tried same as:

OrderDetail.select('unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount')

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

The output i got is without the derived attributes as:

[#<OrderDetail >,#<OrderDetail >]

But i need output as:

[#<OrderDetail regular_price: 43, price_after_discount: 54>,#<OrderDetail regular_price: 54, price_after_discount: 76>]

I tried below query to sort the data.It sorted the data perfectly:

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')

I can access the values using below command:

OrderDetail.select('unit_price,quantity,unit_price*quantity AS extras_1,unit_price*quantity-unit_price*quantity*discount AS extras_2')

above commmand worked because extras_1 and extras_2 are table columns.

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

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.

Aucun commentaire:

Enregistrer un commentaire