Topic: How to make this more efficient

Hi there,

I have the following setup:

- has many projects
- has many resources

- polymorphic (claim_resource)
- employee type
- contractor type
- volunteer type

- each resource has a cost

- generic resource is allocated to a project

Now I want to get total resource type cost for each project. If all the resources are allocated 15% to project 1, I want to total the cost of all employee resource multiplied by the allocation and get the sum.

Right now I'm doing it very inefficiently:

In project.rb (model)

[code type="ruby"]
def total_cost( resources )
    cost = 0
    total_cost = 0

    resources.each { |resource|

      cost = resource.amount
      resource_allocation = resource.claim_resource.project_resource_allocations.find( :first, :conditions => [ "project_id = ? ", id ] )
      allocation = resource_allocation == nil ? 0 : resource_allocation.percent_allocation

      total_cost = total_cost + cost * allocation / 100

I know that code is horrible :-(  But I can't think of a more efficient way of doing that.  Can anyone help?


Re: How to make this more efficient

How about caching the value in the projects table? You can set up a callback for when a resource is created/updated and update the cached value.

Railscasts - Free Ruby on Rails Screencasts

Re: How to make this more efficient

That would do it.  I was hoping for some magical code that will do everything I want it to :-)