Calculations on nested resources

Hi,

I can’t seem to find a solution to the folowing problem.
I have 3 resources that are all bound to eachother like this:

class Item < ActiveRecord::Base
belongs_to :item_category
// has a date and amount attr
end

class ItemCategory < ActiveRecord::Base
has_many :items
has_many :item_tops
// groups the items in categories
end

class ItemTop < ActiveRecord::Base
belongs_to :item_category
// has a start and stop date and an amount attr
end

The thing I would like to do now starts from the ItemTop resource. When
I do a search, it will search for all ItemTop resources where the start
and stop dates are between or equal to 2 dates the user inserted in the
search box.

The result of the search must contain the following data:
the ItemTop amount and the ItemCategory it reflects upon (this I have so
far).

But next, it must show the total sum of the amounts of the Item
resources where the Item.date also resigns between the 2 dates the user
added. I have no idea how I can get this implemented in clean Ruby
style.

I hope someone can help me out with this.

Thank you in advance

I don’t want to come over like a lazy person that just want someone else
to write the code for him. I know a way, but it is not the best idea due
to performance issues.

The way I’m working now it to define the following method in my model:

def actual
total = BigDecimal.new(“0”)
item_category.items.each do |set|
if set.set_date >= start_date && set.set_date <= stop_date
total += set.amount
end
end
return total
end

It gets the job done, but it iterates over every item. Is there a way to
solve this by just retrieve the good items from the database instead of
all the items?

On 12 Jul 2008, at 18:55, Michael R. wrote:

total = BigDecimal.new(“0”)
item_category.items.each do |set|
if set.set_date >= start_date && set.set_date <= stop_date
total += set.amount
end
end

Something like
item_category.items.sum :amount, :conditions => …
?
Fred

Frederick C. wrote:

On 12 Jul 2008, at 18:55, Michael R. wrote:

total = BigDecimal.new(“0”)
item_category.items.each do |set|
if set.set_date >= start_date && set.set_date <= stop_date
total += set.amount
end
end

Something like
item_category.items.sum :amount, :conditions => …
?
Fred

Well I’ll be damned Fred. I didn’t know that this was even possible in
Rails.
Looks like I need more reading :slight_smile:

Thank you for the help