Your mistake was to use fill_at in the order, probably in the default area.
You can fix this using unscoped to exclude default scopes:
Income.unscoped .group('date(filled_at)') .having("date(filled_at) > ?", Date.today - n) .sum(:lines_price)
or
Income.unscoped .group('date(filled_at)') .having("date(filled_at) > ?", Date.today - n) .sum(:lines_price) .order('date(filled_at) ASC')
but I think it's better to use where instead
Income.unscoped .where("date(filled_at) > TIMESTAMP ?", Date.today - n) .group('date(filled_at)') .sum(:lines_price) .order('date(filled_at) ASC')
SQLFiddle
You should be careful using TIMESTAMP, because 2012-12-04 will become 2012-12-04 00:00:00, so if you do not want this day to be used in the results of Date.today - (n - 1)
If you create an index in the fill_at column
create index incomes_filled_at on incomes(filled_at);
migration:
add_index :incomes, :filled_at
and you have a lot of data in this table, the index will be used when filtering. Therefore, the request should be much faster.
So just write tests that are faster (you need to create an index on fill_at if you don't have one).
source share