Reputation: 2665
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:
Upvotes: 0
Views: 61
Reputation: 2674
months = (1..11).map { |m| last_month_end.advance(months: 0 - m) }
where("month_end IN (?)", months)
Or something like that. That would be a more readable and maintainable way of doing what you did above. As someone else said, you can check if a date is in between a start and an end date in SQL.
where("date >= ? AND date <= ?", start_date, end_date)
or (better yet)
where("date BETWEEN ? AND ?", start_date, end_date)
Upvotes: 1