Here's my situation. I have two tables: pledges and pledge\_transactions. When a user makes a pledge, he has only a row in the pledges table.

Later when it comes time to fulfill the pledge, each payment is logged in my pledge\_transactions table.

I need to be able to query all open pledges which means that the sum of the amounts in the transactions table is less than the pledged amount.

Here's what I have so far:

```
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 might be asking yourself why I have that superfluous and ridiculous conditions option specified. The answer is that when I don't force ActiveRecord to acknowledge the pledge\_transactions table in the conditions, it omits it completely, which means my having clause becomes meaningless.

My belief is that I have run into a shortcoming of ActiveRecord.

Ultimately I need to be able to do the following:

* Pledge.open
* Pledge.open.count
* Pledge.open.find(:all, ...)
* etc.

Anybody have a more elegant answer to this problem? Please no suggestions of incrementing a pledges amount\_given field each time a transaction occurs. That feels like a band-aid approach and I'm much more of a fan of keeping the pledge static after it is created and computing the difference.

If I weren't using Rails here, I'd just create a view and be done with it.

Thanks!