Here is my situation. I have two tables: pledges and promises. When a user makes a pledge, he only has a row in the pledge table.
Later, when it comes time to fulfill a promise, each payment is recorded in my pledge_transactions table.
I need to be able to request all open promises, which means that the sum of the amounts in the transaction table is less than the declared amount.
Here is what I still have:
named_scope :open, :group => 'pledges.id', :include => :transactions, :select => 'pledge_transactions.*', :conditions => 'pledge_transactions.id is not null or pledge_transactions.id is null', :having => 'sum(pledge_transactions.amount) < pledges.amount or sum(pledge_transactions.amount) is null'
You may ask yourself why I have this extra and ridiculous version of the conditions. The answer is that when I do not force ActiveRecord to recognize the pledge_transactions table in conditions, it completely excludes it, which means that my article makes sense.
I am convinced that I ran into a lack of ActiveRecord.
Ultimately, I will need to do the following:
- Pledge.open
- Pledge.open.count
- Pledge.open.find (: everything, ...)
- and etc.
Does anyone have a more elegant answer to this problem? Please do not suggest increasing the number of declared amount_given values each time a transaction occurs. This is similar to the group help approach, and I am much more a fan of maintaining static after creating it and calculating the difference.
If I did not use Rails here, I would just create a view and do it with it.
Thanks!