# Virtual user methods

**URL:** <https://www.ruby-forum.com/t/virtual-user-methods/125607>\
**Category:** Rails\
**Created:** [January 10, 2008, 4:02pm UTC](https://www.ruby-forum.com/t/virtual-user-methods/125607 "2008-01-10T16:02:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![fcano](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/e19adc/32.png) [@fcano](https://www.ruby-forum.com/u/fcano)\
**Post date:** [January 10, 2008, 4:02pm UTC](https://www.ruby-forum.com/t/virtual-user-methods/125607/1 "2008-01-10T16:02:16Z")

</div>

Hi,  
I have a table called ‘fruit\_operations’ with this example content:

bananas 6 buy tony  
bananas 3 sell tony  
tomatoes 5 buy tony  
bananas 1 sell john  
tomatoes 5 sell tony  
bananas 2 buy tony

Now I want a @user method that returns for Tony 5 bananas (6-3+2), that  
could be accesed like @user.fruit\_list for example.

I have think that I can implement this with another model called  
FruitList and another table fruit-list that is updated each time we have  
a fruit\_operation but I would like to have something like a “virtual  
table” that only do the calculation then @user.fruit\_list is invoked  
with the information found in fruit\_operations.

How do you recommend implementing this?

In fact this is for a webapp with stocks, operations and the portfolio  
not fruits 😉

---

<div class="post-metadata">

**Author:** ![fcano](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/e19adc/32.png) [@fcano](https://www.ruby-forum.com/u/fcano)\
**Post date:** [January 10, 2008, 4:34pm UTC](https://www.ruby-forum.com/t/virtual-user-methods/125607/2 "2008-01-10T16:34:35Z")

</div>

On 10 Jan 2008, at 15:02, Florencio C. wrote:

> Now I want a @user method that returns for Tony 5 bananas (6-3+2),  
> that  
> could be accesed like @user.fruit\_list for example.

Well supposing, user has\_many fruit\_operations

user.fruit\_operations gets you all of tony’s operations.

Off the back of that you could do

user.fruit\_operations.sum(:quantity, :conditions =\> {:fruit\_type =\>  
‘banana’, :operation\_type =\> ‘sell’})  
and  
user.fruit\_operations.sum(:quantity, :conditions =\> {:fruit\_type =\>  
‘banana’, :operation\_type =\> ‘buy’})

Or if you are only ever interested in the total you could  
sum(IF(operation=‘buy’,1,-1) \* quantity)  
If you’re using this frequently you can bung methods like that in an  
association proxy.

Another way to do this is to have methods on FruitOperation, for example

class FruitOperation  
def self.banana\_count  
sum(:quantity, :conditions =\> {:fruit\_type =\>  
‘banana’, :operation\_type =\> ‘buy’}) -  
sum(:quantity, :conditions =\> {:fruit\_type =\>  
‘banana’, :operation\_type =\> ‘sell’})  
end  
end

You can now do tony.fruit\_operations.banana\_count - You get the  
scoping for free

Fred
