Rails Query Pulling Inaccurate Results

m running Rails 3.0.7, Ruby 1.9.2, and mySQL (local and remote). I have a query which is pulling in records that I don’t understand. The purpose of the query is to total points that users receive from customer jobs they complete.

Models: user, customer, activity

Two weird things seem to happen:

(1) Activity records are pulling in which don’t belong to the user, in fact, when I look at my DB I’m not sure the Activity records even exist (do a sort by user_id in Activity, then I look at the dates when I don’t find match by user_id)

(2) when I look at my Rails server records, it seems to cycle through all of the users instead of just the one I’m looking for which would make it a resource hog even if the calculation was correct.

I have tried the query two ways, but both yield the same [wrong] results. Please help!

in the Activity model, I have this method:

def self.calculate_user_job_points(customer, user_id)
  Activity.sum(:amount , :conditions => [ "job_id IN (?) and user_id =?", customer.jobs, user_id ])
end

I’ve also tried the query this way and it yields the same results:

 Activity.where('job_id =? and user_id =?', customer.jobs, user_id).sum("amount")

When I look in my Rails server command window, it shows that instead of looking for one user, it looks like it is repeating the query for each user (although the results I receive is not all Activity records, and differs from user to user)

I call it like so:

<%= Activity.get_user_flock_rank(@customer, current_user.id) %>

Both the customer and user seem to pass ok as parameters. How do I fix this? Do I need to somehow break this down into two queries? I noticed in the Rails guide for querying, they all seem to be simpler queries for the calculations. Thank you for any help you can provide.

How about this?

 Activity.where('job_id in (?) and user_id =?', customer.job_ids, user_id).sum("amount")

I don't think there's a lot that can be said without seeing the actual sql that gets generated and the result versus the expected result (with some sample data). There's nothing obviously incorrect with what you've written, but then again I'm not 100% store what you're trying to do

Fred