Virtual user methods

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 :wink:

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.

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