I'm stuck with some issues I can't overcome by myself, please help.
What I want to achieve:
I want to get the list of spend per category for the current user for
the last 30 days.
Preferably also sorted by spend, descending (to present it nicely in a
class Category < ActiveRecord::Base
has_many :operations, :through => :amounts
acts_as_tree :order => "name"
class Operation < ActiveRecord::Base
has_many :categories, :through => :amounts
class Amount < ActiveRecord::Base
Amounts table structure:
What I try to do:
@recent_expenses = current_user.categories.find(:all, :include =>
[:amounts, :operations], :conditions => ['operations.date > ? AND
cat_type = "Expense" AND amounts.value <> 0', (Time.now -
First of all, it fails.
I don't know why but it takes ALL the expenses instead of just those
from the last 30 days.
Second, it doesn't obviously neither sum those expenses nor sort it by
I then do in the view:
<% for category in @recent_expenses %>
<%= category.name %>
<%= category.amounts.sum(:value) %><br />
<% end %>
It gives me those summed values but it also fires additional SQL queries
for each category to sum it up. And, as mentioned above, it sums all the
entries, not just from the last month.
I know I'm doing something terribly wrong here.
Are my has_many :through dependencies wrong?
Is my eager loading handled the wrong way?
Am I missing something else?
Any help would be much appreciated.