I’m not sure what “goes wrong” but this is another way to write the query. I didn’t see where your teams table comes into play in your query, so I left it out:
SELECT DISTINCT u., w.
FROM whereusers u
INNER JOIN teams_users tu
ON tu.user_id = u.id
AND tu.team_id = #{self.id.to_s}
INNER JOIN wherenotes w
ON w.user_id = u.id
AND w.note_date = yourdate
I've been watching this conversation play out for a while now.
Tom, I'd like to point out something you're saying which is completely
false (and most likely holding you back from reaching a solution):
"I need to include conditions on the included object. This is not
where eager loading can be used"
Eager loading using the :include option *absolutely* allows you to
have conditions that refer to the relations specified in your
:include.
Not to put too fine a point on it, but what you've described so far is
a *trivial* use-case of ActiveRecord. It's time you started assuming
you are doing something wrong rather than assuming ActiveRecord is
incapable.
Assuming what you've explained so far is accurate, try this. Tail the
development.log file to see the queries being executed:
x = Team.find(:all, :include => :users)
x.first.users.length # should not cause another query to hit the DB
y = Team.find(:all, :include => :users, :conditions =>'users.id is not null')
y.first.users.length # again, no extra hit to DB