Find related record through a has_many through relation

Hey guys, upon further hacking I managed to get this working.
I used sub selects from inner joins.
I'm sure there some way to improve this. Maybe temporary tables?

cc. @abenari, @brocktimus, @brunogh