# Calculations on a virtual attribute

**URL:** <https://www.ruby-forum.com/t/calculations-on-a-virtual-attribute/167073>\
**Category:** Rails\
**Created:** [May 3, 2009, 11:25am UTC](https://www.ruby-forum.com/t/calculations-on-a-virtual-attribute/167073 "2009-05-03T11:25:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![holden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/e36b37/32.png) [@holden](https://www.ruby-forum.com/u/holden)\
**Post date:** [May 3, 2009, 11:25am UTC](https://www.ruby-forum.com/t/calculations-on-a-virtual-attribute/167073/1 "2009-05-03T11:25:05Z")

</div>

I is possible to do calculations on a virtual attribute… such as  
sum, or count

I tried using the same as I would on a DB column but of course that  
doesn’t work. ie. Pricelist.sum(:cyberguide)

I have a table with 2 fields, one with a price and the other with a  
condition then have a virtual attribute which does a calculation:

def cyberguide  
if condition \<= 2  
[price.pricehigh]  
elsif condition == 3  
[price.pricehigh \* 0.9]  
elsif condition == 4  
[price.pricehigh \* 0.5]  
elsif condition == 5  
[price.pricehigh \* 0.25]  
elsif condition == 6  
[price.pricehigh \* 0.2]  
else  
[price.pricehigh \* 0.15]  
end  
end

It works perfectly for individual functions, but how would a sum the  
virtual attribute?

Thanks

---

<div class="post-metadata">

**Author:** ![holden](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/e36b37/32.png) [@holden](https://www.ruby-forum.com/u/holden)\
**Post date:** [May 3, 2009, 11:35am UTC](https://www.ruby-forum.com/t/calculations-on-a-virtual-attribute/167073/2 "2009-05-03T11:35:07Z")

</div>

On May 3, 7:55 am, holden [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I is possible to do calculations on a virtual attribute… such as  
> sum, or count
> 
> I tried using the same as I would on a DB column but of course that  
> doesn’t work. ie. Pricelist.sum(:cyberguide)

You’re going to have to construct an appropriate sql fragment, eg  
according to the docs you can do Pricelist.sum(“2 \* price”) - you just  
need that on steroids.

Fred
