I've done a horrible thing...
I've got a table that contains account balances. It has attributes for the account_id, the amount, and the month_end date. I wanted to query that table for the balances for the last twelve months. But there's gotta be a better way to do it than this.
scope :recent_balances, lambda { { :conditions =>
["month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ?",
last_month_end.to_s,
(last_month_end-1.month).end_of_month.to_s,
(last_month_end-2.month).end_of_month.to_s,
(last_month_end-3.month).end_of_month.to_s,
(last_month_end-4.month).end_of_month.to_s,
(last_month_end-5.month).end_of_month.to_s,
(last_month_end-6.month).end_of_month.to_s,
(last_month_end-7.month).end_of_month.to_s,
(last_month_end-8.month).end_of_month.to_s,
(last_month_end-9.month).end_of_month.to_s,
(last_month_end-10.month).end_of_month.to_s,
(last_month_end-11.month).end_of_month.to_s ] } }
private
def self.last_month_end
last_month_end ||= (Date.today - 1.month).end_of_month
end
My questions are:
- What's the smart way to do this query? (There's no way it's what I just came up with.)
- How can I modify this query to make it more flexible? I'd like to be able to pass in a particular number of months to the query (e.g. query for six months of balances or for 24 months of balances)
month_enda date field or a string?