Before I start, I apologize for a bad title but I could not come up with one that describes my question in a satisfying way. If you come up with a better title, I will gladly switch.
Suppose I have an Account
model and a Transaction
model, and I would like to implement a Account#days_since_balance_was_atleast
method, taking a sum as its sole parameter. What would be an effective way to do this?
Here comes some sample code:
class Transaction < ActiveRecord::Base
validates_presence_of :account_id, :created_at, :amount
belongs_to :account
# Some logic to update account balance at creation...
end
class Account < ActiveRecord::Base
validates_presence_of :balance
has_many :transactions
def days_since_balance_was_atleast(sum)
#How should I implement this?
end
end
Should I use some smart SQL fragment, or perhaps ActiveRecord::Calculations? Loading all transactions and stepping backwards manually seems like a very bad idea (especially since there can be lots of transactions). And if I am stuck with the last approach, do you think it would be smart to retrieve the transactions in batches.
What it should produce (Updated):
# We have the following transactions
# (time is unimportant for the result unless it is 00.00)
# Days ago 0 1 2 3 4 5 6 7
# Amount -20 10 -60 -30 50 50 -100 100
account.balance == 0 # true
days_since_balance_was(100) == 3 # true
So, how would you solve this problem?