generate the correct query when using has_many through